Compare commits

..

4 Commits

214 changed files with 6060 additions and 6585 deletions

View File

@@ -12,28 +12,6 @@ and this project adheres to
<!-- write down unreleased development here --> <!-- write down unreleased development here -->
* [task] Select2 field in task form to allow search for a user (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/167)
* remove "search by phone configuration option": search by phone is now executed by default
* remplacer le classement par ordre alphabétique par un classement par ordre de pertinence, qui tient compte:
* de la présence d'une string avec le nom de la ville;
* de la similarité;
* du fait que la recherche commence par une partie du mot recherché
* ajouter la recherche par numéro de téléphone directement dans la barre de recherche et dans le formulaire recherche avancée;
* ajouter la recherche par date de naissance directement dans la barre de recherche;
* ajouter la recherche par ville dans la recherche avancée
* ajouter un lien vers le ménage dans les résultats de recherche
* ajouter l'id du parcours dans les résultats de recherche
* ajouter le demandeur dans les résultats de recherche
* ajout d'un bouton "recherche avancée" sur la page d'accueil
* [person] create an accompanying course: add client-side validation if no origin (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/210)
* [person] fix bounds for computing current person address: the new address appears immediatly
* [docgen] create a normalizer and serializer for normalization on doc format
## Test releases
### Test release 2021-11-15
* [main] fix adding multiple AddresseDeRelais (combine PickAddressType with ChillCollection) * [main] fix adding multiple AddresseDeRelais (combine PickAddressType with ChillCollection)
* [person]: do not suggest the current household of the person (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/51) * [person]: do not suggest the current household of the person (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/51)
* [person]: display other phone numbers in view + add message in case no others phone numbers (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/184) * [person]: display other phone numbers in view + add message in case no others phone numbers (https://gitlab.com/champs-libres/departement-de-la-vendee/accent-suivi-developpement/-/issues/184)
@@ -48,6 +26,9 @@ and this project adheres to
* [person] do not ask for center any more on person creation * [person] do not ask for center any more on person creation
* [3party] do not ask for center any more on 3party creation * [3party] do not ask for center any more on 3party creation
## Test releases
### Test release 2021-11-08 ### Test release 2021-11-08
* [person]: Display the name of a user when searching after a User (TMS) * [person]: Display the name of a user when searching after a User (TMS)

View File

@@ -91,8 +91,7 @@
}, },
"autoload-dev": { "autoload-dev": {
"psr-4": { "psr-4": {
"App\\": "tests/app/src/", "App\\": "tests/app/src/"
"Chill\\DocGeneratorBundle\\Tests\\": "src/Bundle/ChillDocGeneratorBundle/tests"
} }
}, },
"minimum-stability": "dev", "minimum-stability": "dev",

View File

@@ -23,196 +23,15 @@ Every time an entity is created, viewed or updated, the software check if the us
The user must be granted access to the action on this particular entity, with this scope and center. The user must be granted access to the action on this particular entity, with this scope and center.
TL;DR
=====
Resolve scope and center
------------------------
In a service, resolve the center and scope of an entity
.. code-block:: php
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
use Chill\MainBundle\Security\Resolver\ScopeResolverDispatcher;
class MyService {
private ScopeResolverDispatcher $scopeResolverDispatcher;
private CenterResolverDispatcher $centerResolverDispatcher;
public function myFunction($entity) {
/** @var null|Center[]|Center $center */
$center = $this->centerResolverDispatcher->resolveCenter($entity);
// $center may be null, an array of center, or an instance of Center
if ($this->scopeResolverDispatcher->isConcerned($entity) {
/** @var null|Scope[]|Scope */
$scope = $this-scopeResolverDispatcher->resolveScope($entity);
// $scope may be null, an array of Scope, or an instance of Scope
}
}
}
In twig template, resolve the center:
.. code-block:: twig
{# resolve a center #}
{% if person|chill_resolve_center is not null%}
{% if person|chill_resolve_center is iterable %}
{% set centers = person|chill_resolve_center %}
{% else %}
{% set centers = [ person|chill_resolve_center ] %}
{% endif %}
<span class="open_sansbold">
{{ 'Center'|trans|upper}} :
</span>
{% for c in centers %}
{{ c.name|upper }}
{% if not loop.last %}, {% endif %}
{% endfor %}
{%- endif -%}
In twig template, resolve the scope:
.. code-block:: twig
{% if entity|chill_is_scope_concerned %}
{% if entity|chill_resolve_scope is iterable %}
{% set scopes = entity|chill_resolve_scope %}
{% else %}
{% set scopes = [ entity|chill_resolve_scope ] %}
{% endif %}
<span>Scopes&nbsp;:</span>
{% for s in scopes %}
{{ c.name|localize_translatable_string }}
{% if not loop.last %}, {% endif %}
{% endfor %}
{%- endif -%}
Build a ``Voter``
-----------------
.. code-block:: php
<?php
namespace Chill\DocStoreBundle\Security\Authorization;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\VoterHelperFactoryInterface;
use Chill\MainBundle\Security\Authorization\VoterHelperInterface;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\DocStoreBundle\Entity\PersonDocument;
use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Security;
class PersonDocumentVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
// roles should be stored into constants:
const CREATE = 'CHILL_PERSON_DOCUMENT_CREATE';
const SEE = 'CHILL_PERSON_DOCUMENT_SEE';
const SEE_DETAILS = 'CHILL_PERSON_DOCUMENT_SEE_DETAILS';
const UPDATE = 'CHILL_PERSON_DOCUMENT_UPDATE';
const DELETE = 'CHILL_PERSON_DOCUMENT_DELETE';
protected Security $security;
protected VoterHelperInterface $voterHelper;
public function __construct(
Security $security,
VoterHelperFactoryInterface $voterHelperFactory
) {
$this->security = $security;
// we build here a voter helper. This will ease the operations below.
// when the authorization model is changed, it will be easy to make a different implementation
// of the helper, instead of writing all Voters
$this->voterHelper = $voterHelperFactory
// create a builder with some context
->generate(self::class)
// add the support of given roles for given class:
->addCheckFor(Person::class, [self::SEE, self::CREATE])
->addCheckFor(PersonDocument::class, $this->getRoles())
->build();
}
protected function supports($attribute, $subject)
{
return $this->voterHelper->supports($attribute, $subject);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
// basic check
if (!$token->getUser() instanceof User) {
return false;
}
// we first check the acl for associated elements.
// here, we must be able to see the person associated to the document:
if ($subject instanceof PersonDocument
&& !$this->security->isGranted(PersonVoter::SEE, $subject->getPerson())) {
// not possible to see the associated person ? Then, not possible to see the document!
return false;
}
// the voter helper will implements the logic:
return $this->voterHelper->voteOnAttribute($attribute, $subject, $token);
}
// all the method below are used to register roles into the admin part
public function getRoles()
{
return [
self::CREATE,
self::SEE,
self::SEE_DETAILS,
self::UPDATE,
self::DELETE
];
}
public function getRolesWithoutScope()
{
return array();
}
public function getRolesWithHierarchy()
{
return ['PersonDocument' => $this->getRoles() ];
}
}
From an user point of view From an user point of view
========================== --------------------------
The software is design to allow fine tuned access rights for complicated installation and team structure. The administrators may also decide that every user has the right to see all resources, where team have a more simple structure. The software is design to allow fine tuned access rights for complicated installation and team structure. The administrators may also decide that every user has the right to see all resources, where team have a more simple structure.
Here is an overview of the model. Here is an overview of the model.
Chill can be multi-center Chill can be multi-center
------------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^
Chill is designed to be installed once for social center who work with multiple teams separated, or for social services's federation who would like to share the same installation of the software for all their members. Chill is designed to be installed once for social center who work with multiple teams separated, or for social services's federation who would like to share the same installation of the software for all their members.
@@ -223,7 +42,7 @@ Otherwise, it is not required to create multiple center: Chill can also work for
Obviously, users working in the different centers are not allowed to see the entities (_persons_, _reports_, _activities_) of other centers. But users may be attached to multiple centers: consequently they will be able to see the entities of the multiple centers they are attached to. Obviously, users working in the different centers are not allowed to see the entities (_persons_, _reports_, _activities_) of other centers. But users may be attached to multiple centers: consequently they will be able to see the entities of the multiple centers they are attached to.
Inside center, scope divide team Inside center, scope divide team
-------------------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Users are attached to one or more center and, inside to those center, there may exists differents scopes. The aim of those _scopes_ is to divide the whole team of social worker amongst different departement, for instance: the social team, the psychologist team, the nurse team, the administrative team, ... Each team is granted of different rights amongst scope. For instance, the social team may not see the _activities_ of the psychologist team. The administrative team may see the date & time's activities, but is not allowed to see the detail of those entities (the personal notes, ...). Users are attached to one or more center and, inside to those center, there may exists differents scopes. The aim of those _scopes_ is to divide the whole team of social worker amongst different departement, for instance: the social team, the psychologist team, the nurse team, the administrative team, ... Each team is granted of different rights amongst scope. For instance, the social team may not see the _activities_ of the psychologist team. The administrative team may see the date & time's activities, but is not allowed to see the detail of those entities (the personal notes, ...).
@@ -233,38 +52,8 @@ As entities have only one scopes, if some entities must be shared across two dif
Example: if some activities must be seen and updated between nurses and psychologists, the administrator will create a scope "nurse and psy" and add the ability for both team "nurse" and "psychologist" to "create", "see", and "update" the activities belonging to scope "nurse and psy". Example: if some activities must be seen and updated between nurses and psychologists, the administrator will create a scope "nurse and psy" and add the ability for both team "nurse" and "psychologist" to "create", "see", and "update" the activities belonging to scope "nurse and psy".
Where does the ``scope`` and ``center`` comes from ?
====================================================
Most often, scope and center comes from user's input:
* when person is created, Chill asks the associated center to the user. Then, every entity associated to the user (Activity, ...) is associated to this center;
* when an entity is created, Chill asks the associated scope.
The UI check the model before adding those input into form. If the user hae access to only one center or scope, this scope or center is filled automatically, and the UI does not ask the user. Most of the times, the user does not see "Pick a scope" and "Pick a center" inputs.
Scope and Center are associated to entities through ``ManyToOne`` properties, which are then mapped to ``FOREIGN KEY`` in tables, ...
But sometimes, this implementation does not fits the needs:
* persons are associated to center *geographically*: the address of each person contains lat/lon coordinates, and the center is resolved from this coordinated;
* some would like to associated persons to multiple center, or one center;
* entities are associated to scope through the job reached by "creator" (an user);
* some would like not to use scope at all;
*
For this reasons, associated center and scopes must be resolved programmatically. The default implementation rely on the model association, as described above. But it becomes possible to change the behaviour on different implementations.
Is my entity "concerned" by scopes ?
------------------------------------
Some entities are concerned by scope, some not.
This is also programmatically resolved.
The concepts translated into code The concepts translated into code
=================================== -----------------------------------
.. figure:: /_static/access_control_model.png .. figure:: /_static/access_control_model.png
@@ -292,7 +81,7 @@ At each step of his lifetime (creation, view of the entity and eventually of his
All those action are executed through symfony voters and helpers. All those action are executed through symfony voters and helpers.
How to check authorization ? How to check authorization ?
============================ ----------------------------
Just use the symfony way-of-doing, but do not forget to associate the entity you want to check access. For instance, in controller : Just use the symfony way-of-doing, but do not forget to associate the entity you want to check access. For instance, in controller :
@@ -311,23 +100,34 @@ Just use the symfony way-of-doing, but do not forget to associate the entity you
And in template : And in template :
.. code-block:: twig .. code-block:: html+jinja
{{ if is_granted('CHILL_ENTITY_SEE', entity) %}print something{% endif %} {{ if is_granted('CHILL_ENTITY_SEE', entity) %}print something{% endif %}
Retrieving reachable scopes and centers for a user Retrieving reachable scopes and centers
-------------------------------------------------- ----------------------------------------
The class :class:`Chill\\MainBundle\\Security\\Authorization\\AuthorizationHelperInterface` helps you to get centers and scope reachable by a user. The class :class:`Chill\\MainBundle\\Security\\Authorization\\AuthorizationHelper` helps you to get centers and scope reachable by a user.
Those methods are intentionnaly build to give information about user rights: Those methods are intentionnaly build to give information about user rights:
- getReachableCenters: to get reachable centers for a user - getReachableCenters: to get reachable centers for a user
- getReachableScopes : to get reachable scopes for a user - getReachableScopes : to get reachable scopes for a user
.. note::
The service is reachable through the Depedency injection with the key `chill.main.security.authorization.helper`. Example :
.. code-block:: php
$helper = $container->get('chill.main.security.authorization.helper');
.. todo::
Waiting for a link between our api and this doc, we invite you to read the method signatures `here <https://github.com/Chill-project/Main/blob/add_acl/Security/Authorization/AuthorizationHelper.php>`_
Adding your own roles Adding your own roles
--------------------- =====================
Extending Chill will requires you to define your own roles and rules for your entities. You will have to define your own voter to do so. Extending Chill will requires you to define your own roles and rules for your entities. You will have to define your own voter to do so.
@@ -352,7 +152,7 @@ To create your own roles, you should:
Declare your role Declare your role
^^^^^^^^^^^^^^^^^^ ------------------
To declare new role, implement the class :class:`Chill\\MainBundle\\Security\\ProvideRoleInterface`. To declare new role, implement the class :class:`Chill\\MainBundle\\Security\\ProvideRoleInterface`.
@@ -412,8 +212,69 @@ Example of an implementation of :class:`Chill\\MainBundle\\Security\\ProvideRole
} }
Implement your voter
--------------------
Inside this class, you might use the :class:`Chill\\MainBundle\\Security\\Authorization\\AuthorizationHelper` to check permission (do not re-invent the wheel). This is a real-world example:
.. code-block:: php
namespace Chill\ReportBundle\Security\Authorization;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
class ReportVoter extends AbstractChillVoter
{
const CREATE = 'CHILL_REPORT_CREATE';
const SEE = 'CHILL_REPORT_SEE';
const UPDATE = 'CHILL_REPORT_UPDATE';
/**
*
* @var AuthorizationHelper
*/
protected $helper;
public function __construct(AuthorizationHelper $helper)
{
$this->helper = $helper;
}
protected function getSupportedAttributes()
{
return array(self::CREATE, self::SEE, self::UPDATE);
}
protected function getSupportedClasses()
{
return array('Chill\ReportBundle\Entity\Report');
}
protected function isGranted($attribute, $report, $user = null)
{
if (! $user instanceof \Chill\MainBundle\Entity\User){
return false;
}
return $this->helper->userHasAccess($user, $report, $attribute);
}
}
Then, you will have to declare the service and tag it as a voter :
.. code-block:: yaml
services:
chill.report.security.authorization.report_voter:
class: Chill\ReportBundle\Security\Authorization\ReportVoter
arguments:
- "@chill.main.security.authorization.helper"
tags:
- { name: security.voter }
Adding role hierarchy Adding role hierarchy
^^^^^^^^^^^^^^^^^^^^^ ---------------------
You should prepend Symfony's security component directly from your code. You should prepend Symfony's security component directly from your code.
@@ -451,484 +312,3 @@ You should prepend Symfony's security component directly from your code.
} }
Implement your voter
^^^^^^^^^^^^^^^^^^^^
Most of the time, Voter will check that:
1. The given role is reachable (= ``$attribute``)
2. for the given center,
3. and, if any, for the given role
4. if the entity is associated to another entity, this entity should be, at least, viewable by the user.
Thats what we call the "autorization logic". But this logic may be replace by a new one, and developers should take care of it.
Then voter implementation should take care of:
* check the access to associated entities. For instance, if an ``Activity`` is associated to a ``Person``, the voter should first check that the user can show the associated ``Person``;
* as far as possible, delegates the check for associated center, scopes, and check for authorization using the authorization logic. VoterHelper will ease the most common operation of this logic.
This is an example of implementation:
.. code-block:: php
<?php
namespace Chill\DocStoreBundle\Security\Authorization;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\VoterHelperFactoryInterface;
use Chill\MainBundle\Security\Authorization\VoterHelperInterface;
use Chill\DocStoreBundle\Entity\PersonDocument;
use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
class PersonDocumentVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
protected Security $security;
protected VoterHelperInterface $voterHelper;
public function __construct(
Security $security,
VoterHelperFactoryInterface $voterHelperFactory
) {
$this->security = $security;
// we build here a voter helper. This will ease the operations below.
// when the authorization model is changed, it will be easy to make a different implementation
// of the helper, instead of writing all Voters
$this->voterHelper = $voterHelperFactory
// create a builder with some context
->generate(self::class)
// add the support of given roles for given class:
->addCheckFor(Person::class, [self::SEE, self::CREATE])
->addCheckFor(PersonDocument::class, $this->getRoles())
->build();
}
protected function supports($attribute, $subject)
{
return $this->voterHelper->supports($attribute, $subject);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
// basic check
if (!$token->getUser() instanceof User) {
return false;
}
// we first check the acl for associated elements.
// here, we must be able to see the person associated to the document:
if ($subject instanceof PersonDocument
&& !$this->security->isGranted(PersonVoter::SEE, $subject->getPerson())) {
// not possible to see the associated person ? Then, not possible to see the document!
return false;
}
// the voter helper will implements the logic of checking:
// 1. that the center is reachable
// 2. for this given entity
// 3. for this given scope
// 4. and for the given role
return $this->voterHelper->voteOnAttribute($attribute, $subject, $token);
}
public function getRoles()
{
// ...
}
public function getRolesWithoutScope()
{
// ...
}
public function getRolesWithHierarchy()
{
// ...
}
}
Then, you will have to declare the service and tag it as a voter :
.. code-block:: yaml
services:
chill.report.security.authorization.report_voter:
class: Chill\ReportBundle\Security\Authorization\ReportVoter
arguments:
- "@chill.main.security.authorization.helper"
tags:
- { name: security.voter }
How to resolve scope and center programmatically ?
==================================================
In a service, resolve the center and scope of an entity
.. code-block:: php
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
use Chill\MainBundle\Security\Resolver\ScopeResolverDispatcher;
class MyService {
private ScopeResolverDispatcher $scopeResolverDispatcher;
private CenterResolverDispatcher $centerResolverDispatcher;
public function myFunction($entity) {
/** @var null|Center[]|Center $center */
$center = $this->centerResolverDispatcher->resolveCenter($entity);
// $center may be null, an array of center, or an instance of Center
if ($this->scopeResolverDispatcher->isConcerned($entity) {
/** @var null|Scope[]|Scope */
$scope = $this-scopeResolverDispatcher->resolveScope($entity);
// $scope may be null, an array of Scope, or an instance of Scope
}
}
}
In twig template, resolve the center:
.. code-block:: twig
{# resolve a center #}
{% if person|chill_resolve_center is not null%}
{% if person|chill_resolve_center is iterable %}
{% set centers = person|chill_resolve_center %}
{% else %}
{% set centers = [ person|chill_resolve_center ] %}
{% endif %}
<span class="open_sansbold">
{{ 'Center'|trans|upper}} :
</span>
{% for c in centers %}
{{ c.name|upper }}
{% if not loop.last %}, {% endif %}
{% endfor %}
{%- endif -%}
In twig template, resolve the scope:
.. code-block:: twig
{% if entity|chill_is_scope_concerned %}
{% if entity|chill_resolve_scope is iterable %}
{% set scopes = entity|chill_resolve_scope %}
{% else %}
{% set scopes = [ entity|chill_resolve_scope ] %}
{% endif %}
<span>Scopes&nbsp;:</span>
{% for s in scopes %}
{{ c.name|localize_translatable_string }}
{% if not loop.last %}, {% endif %}
{% endfor %}
{%- endif -%}
What is the default implementation of Scope and Center resolver ?
-----------------------------------------------------------------
By default, the implementation rely on association into entities.
* implements ``Chill\MainBundle\Entity\HasCenterInterface`` on entities which have one or any center;
* implements ``Chill\MainBundle\Entity\HasCentersInterface`` on entities which have one, multiple or any centers;
* implements ``Chill\MainBundle\Entity\HasScopeInterface`` on entities which have one or any scope;
* implements ``Chill\MainBundle\Entity\HasScopesInterface`` on entities which have one or any scopes;
Then, the default implementation will resolve the center and scope based on the implementation in your model.
How to change the default behaviour ?
-------------------------------------
Implements those interface into services:
* ``Chill\MainBundle\Security\Resolver\CenterResolverInterface``;
* ``Chill\MainBundle\Security\Resolver\ScopeResolverInterface``;
Authorization into lists and index pages
========================================
Due to the fact that authorization model may be overriden, "list" and "index" pages should not rely on center and scope from controller. This must be delegated to dedicated service, which will be aware of the authorization model. We call them ``ACLAwareRepository``. This service must implements an interface, in order to allow to change the implementation.
The controller **must not** performs any DQL or SQL query.
Example in a controller:
.. code-block:: php
namespace Chill\TaskBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Chill\TaskBundle\Repository\SingleTaskAclAwareRepositoryInterface;
final class SingleTaskController extends AbstractController
{
private SingleTaskAclAwareRepositoryInterface $singleTaskAclAwareRepository;
/**
*
* @Route(
* "/{_locale}/task/single-task/list",
* name="chill_task_singletask_list"
* )
*/
public function listAction(
Request $request
) {
$this->denyAccessUnlessGranted(TaskVoter::SHOW, null);
$nb = $this->singleTaskAclAwareRepository->countByAllViewable(
'', // search pattern
[] // search flags
);
$paginator = $this->paginatorFactory->create($nb);
if (0 < $nb) {
$tasks = $this->singleTaskAclAwareRepository->findByAllViewable(
'', // search pattern
[] // search flags
$paginator->getCurrentPageFirstItemNumber(),
$paginator->getItemsPerPage(),
// ordering:
[
'startDate' => 'DESC',
'endDate' => 'DESC',
]
);
} else {
$tasks = [];
}
return $this->render('@ChillTask/SingleTask/List/index.html.twig', [
'tasks' => $tasks,
'paginator' => $paginator,
'filter_order' => $filterOrder
]);
}
}
Writing ``ACLAwareRepository``
------------------------------
The ACLAwareRepository should rely on interfaces
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As described above, the ACLAwareRepository will perform the query for listing entities, and take care of authorization.
Those "ACLAwareRepositories" must be described into ``interfaces``.
The service must rely on this interface, and not on the default implementation.
Example: at first, we design an interface for listing ``SingleTask`` entities:
.. code-block:: php
<?php
namespace Chill\TaskBundle\Repository;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
interface SingleTaskAclAwareRepositoryInterface
{
/**
* @return SingleTask[]|array
*/
public function findByCurrentUsersTasks(?string $pattern = null, ?array $flags = [], ?int $start = 0, ?int $limit = 50, ?array $orderBy = []): array;
public function countByCurrentUsersTasks(?string $pattern = null, ?array $flags = []): int;
public function countByAllViewable(
?string $pattern = null,
?array $flags = []
): int;
/**
* @return SingleTask[]|array
*/
public function findByAllViewable(
?string $pattern = null,
?array $flags = [],
?int $start = 0,
?int $limit = 50,
?array $orderBy = []
): array;
}
Implements this interface and register the interface as an alias for the implementation.
.. code-block:: yaml
services:
Chill\TaskBundle\Repository\SingleTaskAclAwareRepository:
autowire: true
autoconfigure: true
Chill\TaskBundle\Repository\SingleTaskAclAwareRepositoryInterface: '@Chill\TaskBundle\Repository\SingleTaskAclAwareRepository'
Write the basic implementation for re-use: separate authorization logic and search logic
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The logic of such repository may be separated into two logic:
* the authorization logic (show only entities that the user is allowed to see);
* the search logic (filter entities on some criterias).
This logic should be separated into your implementation.
Considering this simple interface:
.. code-block:: php
interface MyEntityACLAwareRepositoryInterface {
public function countByAuthorized(array $criterias): int;
public function findByAuthorized(array $criteria, int $start, int $limit, array $orderBy): array;
}
The base implementation should separate the logic to allow an easy reuse. Here, the method ``buildQuery`` build a basic query without authorization logic, which can be re-used. The authorization logic is dedicated to a private method. For ease of user, the logic of adding ordering criterias and pagination parameters (``$start`` and ``$limit``) are also delegated to a public method.
.. code-block:: php
namespace Chill\MyBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
final class MyEntityACLAwareRepository implements MyEntityACLAwareRepositoryInterface {
private EntityManagerInterface $em;
// constructor omitted
public function countByAuthorized(array $criterias): int
{
$qb = $this->buildQuery($criterias);
return $this->addAuthorizations($qb)->select("COUNT(e)")->getQuery()->getResult()->getSingleScalarResult();
}
public function findByAuthorized(array $criteria, int $start, int $limit, array $orderBy): array
{
$qb = $this->buildQuery($criterias);
return $this->getResult($this->addAuthorizations($qb), $start, $limit, $orderBy);
}
public function getResult(QueryBuilder $qb, int $start, int $limit, array $orderBy): array
{
$qb
->setFirstResult($start)
->setMaxResults($limit)
;
// add order by logic
return $qb->getQuery()->getResult();
}
public function buildQuery(array $criterias): QueryBuilder
{
$qb = $this->em->createQueryBuilder();
// implement you logic with search criteria here
return $qb;
}
private function addAuthorizations(QueryBuilder $qb): QueryBuilder
{
// add authorization logic here
return $qb;
}
}
Once this logic is executed, it becomes easy to make a new implementation of the repository:
.. code-block:: php
namespace Chill\MyOtherBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Chill\MyBundle\Repository\MyEntityACLAwareRepository
final class AnotherEntityACLAwareRepository implements MyEntityACLAwareRepositoryInterface {
private EntityManagerInterface $em;
private \Chill\MyBundle\Repository\MyEntityACLAwareRepository $initial;
public function __construct(
EntityManagerInterface $em,
\Chill\MyBundle\Repository\MyEntityACLAwareRepository $initial
) {
$this->em = $em;
$this->initial = $initial;
}
public function countByAuthorized(array $criterias): int
{
$qb = $this->initial->buildQuery($criterias);
return $this->addAuthorizations($qb)->select("COUNT(e)")->getQuery()->getResult()->getSingleScalarResult();
}
public function findByAuthorized(array $criteria, int $start, int $limit, array $orderBy): array
{
$qb = $this->initial->buildQuery($criterias);
return $this->initial->getResult($this->addAuthorizations($qb), $start, $limit, $orderBy);
}
private function addAuthorizations(QueryBuilder $qb): QueryBuilder
{
// add a different authorization logic here
return $qb;
}
}
Then, register this service and decorates the old one:
.. code-block:: yaml
services:
Chill\MyOtherBundle\Repository\AnotherEntityACLAwareRepository:
autowire: true
autoconfigure: true
decorates: Chill\MyBundle\Repository\MyEntityACLAwareRepositoryInterface:

File diff suppressed because it is too large Load Diff

View File

@@ -1,131 +0,0 @@
parameters:
ignoreErrors:
-
message: "#^Implicit array creation is not allowed \\- variable \\$centers might not exist\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Entity/AccompanyingPeriod.php
-
message: "#^Access to an undefined property Chill\\\\PersonBundle\\\\Entity\\\\Person\\:\\:\\$currentHouseholdParticipationAt\\.$#"
count: 3
path: src/Bundle/ChillPersonBundle/Entity/Person.php
-
message: "#^Access to an undefined property Chill\\\\PersonBundle\\\\Entity\\\\Household\\\\PersonHouseholdAddress\\:\\:\\$relation\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Entity/Household/PersonHouseholdAddress.php
-
message: "#^Access to an undefined property Chill\\\\PersonBundle\\\\Entity\\\\AccompanyingPeriod\\:\\:\\$work\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Entity/AccompanyingPeriod.php
-
message: "#^Undefined variable\\: \\$person$#"
count: 1
path: src/Bundle/ChillActivityBundle/Repository/ActivityACLAwareRepository.php
-
message: "#^Access to an undefined property Chill\\\\PersonBundle\\\\Household\\\\MembersEditorFactory\\:\\:\\$validator\\.$#"
count: 2
path: src/Bundle/ChillPersonBundle/Household/MembersEditorFactory.php
-
message: "#^Parameter \\$action of method Chill\\\\PersonBundle\\\\Repository\\\\AccompanyingPeriod\\\\AccompanyingPeriodWorkRepository\\:\\:buildQueryBySocialActionWithDescendants\\(\\) has invalid type Chill\\\\PersonBundle\\\\Repository\\\\AccompanyingPeriod\\\\SocialAction\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Repository/AccompanyingPeriod/AccompanyingPeriodWorkRepository.php
-
message: "#^Parameter \\$action of method Chill\\\\PersonBundle\\\\Repository\\\\AccompanyingPeriod\\\\AccompanyingPeriodWorkRepository\\:\\:countBySocialActionWithDescendants\\(\\) has invalid type Chill\\\\PersonBundle\\\\Repository\\\\AccompanyingPeriod\\\\SocialAction\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Repository/AccompanyingPeriod/AccompanyingPeriodWorkRepository.php
-
message: "#^Undefined variable\\: \\$action$#"
count: 1
path: src/Bundle/ChillPersonBundle/Repository/AccompanyingPeriod/AccompanyingPeriodWorkRepository.php
-
message: "#^Undefined variable\\: \\$limit$#"
count: 1
path: src/Bundle/ChillPersonBundle/Repository/AccompanyingPeriod/AccompanyingPeriodWorkRepository.php
-
message: "#^Undefined variable\\: \\$offset$#"
count: 1
path: src/Bundle/ChillPersonBundle/Repository/AccompanyingPeriod/AccompanyingPeriodWorkRepository.php
-
message: "#^Undefined variable\\: \\$orderBy$#"
count: 1
path: src/Bundle/ChillPersonBundle/Repository/AccompanyingPeriod/AccompanyingPeriodWorkRepository.php
-
message: "#^Variable variables are not allowed\\.$#"
count: 4
path: src/Bundle/ChillPersonBundle/Search/PersonSearch.php
-
message: "#^Function Chill\\\\PersonBundle\\\\Serializer\\\\Normalizer\\\\·\\\\is_array not found\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Serializer/Normalizer/MembersEditorNormalizer.php
-
message: "#^Undefined variable\\: \\$value$#"
count: 1
path: src/Bundle/ChillPersonBundle/Validator/Constraints/AccompanyingPeriod/LocationValidityValidator.php
-
message: "#^Undefined variable\\: \\$choiceSlug$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Undefined variable\\: \\$choiceSlug$#"
count: 1
path: src/Bundle/ChillReportBundle/Export/Export/ReportList.php
-
message: "#^Undefined variable\\: \\$type$#"
count: 1
path: src/Bundle/ChillTaskBundle/Controller/TaskController.php
-
message: "#^Call to an undefined method Chill\\\\MainBundle\\\\CRUD\\\\Controller\\\\AbstractCRUDController\\:\\:getRoleFor\\(\\)\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/CRUD/Controller/AbstractCRUDController.php
-
message: "#^Call to an undefined method Chill\\\\MainBundle\\\\Controller\\\\UserController\\:\\:createEditForm\\(\\)\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Controller/UserController.php
-
message: "#^Undefined variable\\: \\$current$#"
count: 1
path: src/Bundle/ChillMainBundle/Pagination/PageGenerator.php
-
message: "#^Call to an undefined method Chill\\\\MainBundle\\\\Security\\\\Authorization\\\\AbstractChillVoter\\:\\:getSupportedAttributes\\(\\)\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Security/Authorization/AbstractChillVoter.php
-
message: "#^Call to an undefined method Chill\\\\MainBundle\\\\Security\\\\Authorization\\\\AbstractChillVoter\\:\\:getSupportedClasses\\(\\)\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Security/Authorization/AbstractChillVoter.php
-
message: "#^Call to an undefined method Chill\\\\MainBundle\\\\Security\\\\Authorization\\\\AbstractChillVoter\\:\\:isGranted\\(\\)\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Security/Authorization/AbstractChillVoter.php
-
message: "#^Access to an undefined property Chill\\\\PersonBundle\\\\Controller\\\\PersonController\\:\\:\\$security\\.$#"
count: 3
path: src/Bundle/ChillPersonBundle/Controller/PersonController.php
-
message: "#^Call to an undefined method Chill\\\\ThirdPartyBundle\\\\Form\\\\Type\\\\PickThirdPartyTypeCategoryType\\:\\:transform\\(\\)\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Form/Type/PickThirdPartyTypeCategoryType.php

View File

@@ -1,852 +0,0 @@
parameters:
ignoreErrors:
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/DataFixtures/ORM/LoadActivitytACL.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Entity/Activity.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Entity/ActivityReason.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Entity/ActivityReasonCategory.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Export/Export/ListActivity.php
-
message: "#^Method Chill\\\\ActivityBundle\\\\Export\\\\Export\\\\StatActivityDuration\\:\\:getDescription\\(\\) should return string but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Export/Export/StatActivityDuration.php
-
message: "#^Method Chill\\\\ActivityBundle\\\\Export\\\\Export\\\\StatActivityDuration\\:\\:getTitle\\(\\) should return string but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Export/Export/StatActivityDuration.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Form/ActivityType.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Form/ActivityType.php
-
message: "#^Only booleans are allowed in &&, mixed given on the right side\\.$#"
count: 3
path: src/Bundle/ChillActivityBundle/Form/ActivityType.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 2
path: src/Bundle/ChillActivityBundle/Form/ActivityType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Menu/AdminMenuBuilder.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Repository/ActivityACLAwareRepository.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Security/Authorization/ActivityStatsVoter.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillActivityBundle/Timeline/TimelineActivityProvider.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillAsideActivityBundle/src/Form/AsideActivityFormType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillAsideActivityBundle/src/Menu/AdminMenuBuilder.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 3
path: src/Bundle/ChillBudgetBundle/Form/ChargeType.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 2
path: src/Bundle/ChillBudgetBundle/Form/ResourceType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillBudgetBundle/Security/Authorization/BudgetElementVoter.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillCalendarBundle/Entity/Calendar.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Command/CreateFieldsOnGroupCommand.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Controller/CustomFieldsGroupController.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/AbstractCustomField.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 3
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldChoice.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 4
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldChoice.php
-
message: "#^Method Chill\\\\CustomFieldsBundle\\\\CustomFields\\\\CustomFieldChoice\\:\\:buildForm\\(\\) should return Symfony\\\\Component\\\\Form\\\\FormTypeInterface but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldChoice.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldDate.php
-
message: "#^Method Chill\\\\CustomFieldsBundle\\\\CustomFields\\\\CustomFieldDate\\:\\:buildForm\\(\\) should return Symfony\\\\Component\\\\Form\\\\FormTypeInterface but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldDate.php
-
message: "#^Method Chill\\\\CustomFieldsBundle\\\\CustomFields\\\\CustomFieldLongChoice\\:\\:buildForm\\(\\) should return Symfony\\\\Component\\\\Form\\\\FormTypeInterface but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldLongChoice.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldNumber.php
-
message: "#^Method Chill\\\\CustomFieldsBundle\\\\CustomFields\\\\CustomFieldNumber\\:\\:buildForm\\(\\) should return Symfony\\\\Component\\\\Form\\\\FormTypeInterface but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldNumber.php
-
message: "#^Method Chill\\\\CustomFieldsBundle\\\\CustomFields\\\\CustomFieldText\\:\\:buildForm\\(\\) should return Symfony\\\\Component\\\\Form\\\\FormTypeInterface but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldText.php
-
message: "#^Method Chill\\\\CustomFieldsBundle\\\\CustomFields\\\\CustomFieldTitle\\:\\:buildForm\\(\\) should return Symfony\\\\Component\\\\Form\\\\FormTypeInterface but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldTitle.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Entity/CustomField.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Entity/CustomFieldsGroup.php
-
message: "#^Only booleans are allowed in a negated boolean, mixed given\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Form/CustomFieldType.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillDocStoreBundle/Entity/DocumentCategory.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Entity/Participation.php
-
message: "#^Method Chill\\\\EventBundle\\\\Entity\\\\Participation\\:\\:offsetGet\\(\\) should return mixed but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Entity/Participation.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Form/ChoiceLoader/EventChoiceLoader.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Form/ChoiceLoader/EventChoiceLoader.php
-
message: "#^Parameter \\$resolver of method Chill\\\\EventBundle\\\\Form\\\\EventTypeType\\:\\:setDefaultOptions\\(\\) has invalid type Symfony\\\\Component\\\\OptionsResolver\\\\OptionsResolverInterface\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Form/EventTypeType.php
-
message: "#^Parameter \\$resolver of method Chill\\\\EventBundle\\\\Form\\\\RoleType\\:\\:setDefaultOptions\\(\\) has invalid type Symfony\\\\Component\\\\OptionsResolver\\\\OptionsResolverInterface\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Form/RoleType.php
-
message: "#^Parameter \\$resolver of method Chill\\\\EventBundle\\\\Form\\\\StatusType\\:\\:setDefaultOptions\\(\\) has invalid type Symfony\\\\Component\\\\OptionsResolver\\\\OptionsResolverInterface\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Form/StatusType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Form/Type/PickEventType.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2
path: src/Bundle/ChillEventBundle/Search/EventSearch.php
-
message: "#^Method Chill\\\\EventBundle\\\\Search\\\\EventSearch\\:\\:renderResult\\(\\) should return string but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillEventBundle/Search/EventSearch.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillEventBundle/Security/Authorization/EventVoter.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillEventBundle/Security/Authorization/ParticipationVoter.php
-
message: "#^Casting to string something that's already string\\.$#"
count: 5
path: src/Bundle/ChillFamilyMembersBundle/Entity/AbstractFamilyMember.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 2
path: src/Bundle/ChillFamilyMembersBundle/Form/FamilyMemberType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillFamilyMembersBundle/Security/Voter/FamilyMemberVoter.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/CRUD/Controller/CRUDController.php
-
message: "#^Parameter \\$scope of method Chill\\\\MainBundle\\\\CRUD\\\\Controller\\\\CRUDController\\:\\:getReachableCenters\\(\\) has invalid type Chill\\\\MainBundle\\\\CRUD\\\\Controller\\\\Scope\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/CRUD/Controller/CRUDController.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/CRUD/Resolver/Resolver.php
-
message: "#^Method Chill\\\\MainBundle\\\\CRUD\\\\Resolver\\\\Resolver\\:\\:getConfigValue\\(\\) should return string but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/CRUD/Resolver/Resolver.php
-
message: "#^Call to function array_search\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/CRUD/Routing/CRUDRoutesLoader.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/CRUD/Routing/CRUDRoutesLoader.php
-
message: "#^Method Chill\\\\MainBundle\\\\Command\\\\ChillImportUsersCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/ChillImportUsersCommand.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/ChillImportUsersCommand.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Command/ChillUserSendRenewPasswordCodeCommand.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/ChillUserSendRenewPasswordCodeCommand.php
-
message: "#^Method Chill\\\\MainBundle\\\\Command\\\\ChillUserSendRenewPasswordCodeCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/ChillUserSendRenewPasswordCodeCommand.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Command/LoadAndUpdateLanguagesCommand.php
-
message: "#^Method Chill\\\\MainBundle\\\\Command\\\\LoadAndUpdateLanguagesCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/LoadAndUpdateLanguagesCommand.php
-
message: "#^Only booleans are allowed in a negated boolean, mixed given\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Command/LoadAndUpdateLanguagesCommand.php
-
message: "#^Method Chill\\\\MainBundle\\\\Command\\\\LoadCountriesCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/LoadCountriesCommand.php
-
message: "#^Method Chill\\\\MainBundle\\\\Command\\\\LoadPostalCodesCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/LoadPostalCodesCommand.php
-
message: "#^Method Chill\\\\MainBundle\\\\Command\\\\SetPasswordCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/SetPasswordCommand.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Controller/PasswordController.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Controller/PostalCodeController.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/DataFixtures/ORM/LoadLanguages.php
-
message: "#^Call to function array_search\\(\\) requires parameter \\#3 to be set\\.$#"
count: 5
path: src/Bundle/ChillMainBundle/DependencyInjection/CompilerPass/ExportsCompilerPass.php
-
message: "#^Call to function array_search\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/DependencyInjection/CompilerPass/SearchableServicesCompilerPass.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/DependencyInjection/Configuration.php
-
message: "#^Call to function array_search\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/DependencyInjection/Widget/AbstractWidgetsCompilerPass.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/DependencyInjection/Widget/AbstractWidgetsCompilerPass.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/DependencyInjection/Widget/AbstractWidgetsCompilerPass.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Entity/Address.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Entity/Embeddable/CommentEmbeddable.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Entity/User.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Entity/User.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 6
path: src/Bundle/ChillMainBundle/Export/ExportManager.php
-
message: "#^Only booleans are allowed in a ternary operator condition, mixed given\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Export/Formatter/SpreadsheetListFormatter.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Form/ChoiceLoader/PostalCodeChoiceLoader.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Form/DataMapper/AddressDataMapper.php
-
message: "#^Only booleans are allowed in a negated boolean, mixed given\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Form/Type/AddressType.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Form/Type/AddressType.php
-
message: "#^Only booleans are allowed in a negated boolean, mixed given\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Form/Type/ChillTextareaType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Form/Type/ComposedRoleScopeType.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 3
path: src/Bundle/ChillMainBundle/Form/Type/DataTransformer/DateIntervalTransformer.php
-
message: "#^Only booleans are allowed in a negated boolean, mixed given\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Form/Type/DataTransformer/ObjectToIdTransformer.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Form/Type/Export/PickCenterType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Form/Type/TranslatableStringFormType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Phonenumber/PhonenumberHelper.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Phonenumber/PhonenumberHelper.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Search/Entity/SearchUserApiProvider.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Security/Authorization/AbstractChillVoter.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Security/Authorization/DefaultVoterHelper.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Security/ParentRoleHelper.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Security/PasswordRecover/PasswordRecoverEvent.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Security/PasswordRecover/PasswordRecoverVoter.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Security/PasswordRecover/TokenManager.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 3
path: src/Bundle/ChillMainBundle/Templating/Entity/AddressRender.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Timeline/TimelineBuilder.php
-
message: "#^Method Chill\\\\MainBundle\\\\Timeline\\\\TimelineBuilder\\:\\:getTemplateData\\(\\) should return array but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Timeline/TimelineBuilder.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Validation/Validator/RoleScopeScopePresence.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Validation/Validator/ValidPhonenumber.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Actions/Remove/PersonMove.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Actions/Remove/PersonMove.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/CRUD/Controller/OneToOneEntityPersonCRUDController.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Command/ChillPersonMoveCommand.php
-
message: "#^Method Chill\\\\PersonBundle\\\\Command\\\\ChillPersonMoveCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Command/ChillPersonMoveCommand.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Command/ChillPersonMoveCommand.php
-
message: "#^Call to function array_search\\(\\) requires parameter \\#3 to be set\\.$#"
count: 3
path: src/Bundle/ChillPersonBundle/Command/ImportPeopleFromCSVCommand.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 3
path: src/Bundle/ChillPersonBundle/Command/ImportPeopleFromCSVCommand.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 6
path: src/Bundle/ChillPersonBundle/Command/ImportPeopleFromCSVCommand.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Controller/PersonController.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/DependencyInjection/CompilerPass/AccompanyingPeriodTimelineCompilerPass.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Entity/AccompanyingPeriod.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Entity/Person.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2
path: src/Bundle/ChillPersonBundle/Entity/PersonPhone.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillPersonBundle/Export/AbstractAccompanyingPeriodExportElement.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Aggregator/CountryOfBirthAggregator.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Aggregator/NationalityAggregator.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 3
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Filter/GenderFilter.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Form/ChoiceLoader/PersonChoiceLoader.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Form/ChoiceLoader/PersonChoiceLoader.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Form/DataMapper/PersonAltNameDataMapper.php
-
message: "#^Only booleans are allowed in a ternary operator condition, mixed given\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Form/Type/PersonAltNameType.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Form/Type/PersonPhoneType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Form/Type/PickPersonType.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Household/MembersEditor.php
-
message: "#^Method Chill\\\\PersonBundle\\\\Repository\\\\AccompanyingPeriod\\\\AccompanyingPeriodWorkRepository\\:\\:buildQueryBySocialActionWithDescendants\\(\\) has invalid return type Chill\\\\PersonBundle\\\\Repository\\\\AccompanyingPeriod\\\\QueryBuilder\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Repository/AccompanyingPeriod/AccompanyingPeriodWorkRepository.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 2
path: src/Bundle/ChillPersonBundle/Repository/PersonRepository.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 3
path: src/Bundle/ChillPersonBundle/Search/PersonSearch.php
-
message: "#^Method Chill\\\\PersonBundle\\\\Search\\\\PersonSearch\\:\\:renderResult\\(\\) should return string but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Search/PersonSearch.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Search/SearchPersonApiProvider.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Serializer/Normalizer/AccompanyingPeriodWorkDenormalizer.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2
path: src/Bundle/ChillPersonBundle/Templating/Entity/ClosingMotiveRender.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Timeline/AbstractTimelineAccompanyingPeriod.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillReportBundle/DataFixtures/ORM/LoadReportACL.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillReportBundle/DataFixtures/ORM/LoadReports.php
-
message: "#^Method Chill\\\\ReportBundle\\\\DataFixtures\\\\ORM\\\\LoadReports\\:\\:getRandomChoice\\(\\) should return array\\<string\\>\\|string but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillReportBundle/DataFixtures/ORM/LoadReports.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 4
path: src/Bundle/ChillReportBundle/Export/Export/ReportList.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2
path: src/Bundle/ChillReportBundle/Export/Export/ReportList.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillReportBundle/Security/Authorization/ReportVoter.php
-
message: "#^Method Chill\\\\ReportBundle\\\\Security\\\\Authorization\\\\ReportVoter\\:\\:supports\\(\\) should return bool but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillReportBundle/Security/Authorization/ReportVoter.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 4
path: src/Bundle/ChillReportBundle/Timeline/TimelineReportProvider.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/DataFixtures/ORM/LoadTaskACL.php
-
message: "#^Casting to string something that's already string\\.$#"
count: 3
path: src/Bundle/ChillTaskBundle/Entity/AbstractTask.php
-
message: "#^Only booleans are allowed in an if condition, mixed given\\.$#"
count: 2
path: src/Bundle/ChillTaskBundle/Form/SingleTaskListType.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/Repository/SingleTaskAclAwareRepository.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 5
path: src/Bundle/ChillTaskBundle/Repository/SingleTaskRepository.php
-
message: "#^Method Chill\\\\TaskBundle\\\\Timeline\\\\SingleTaskTaskLifeCycleEventTimelineProvider\\:\\:getTransitionByName\\(\\) should return Symfony\\\\Component\\\\Workflow\\\\Transition but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/Timeline/SingleTaskTaskLifeCycleEventTimelineProvider.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/Timeline/TaskLifeCycleEventTimelineProvider.php
-
message: "#^Method Chill\\\\TaskBundle\\\\Timeline\\\\TaskLifeCycleEventTimelineProvider\\:\\:getTransitionByName\\(\\) should return Symfony\\\\Component\\\\Workflow\\\\Transition but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/Timeline/TaskLifeCycleEventTimelineProvider.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/DependencyInjection/CompilerPass/ThirdPartyTypeCompilerPass.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 4
path: src/Bundle/ChillThirdPartyBundle/Entity/ThirdParty.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Form/ChoiceLoader/ThirdPartyChoiceLoader.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Form/ChoiceLoader/ThirdPartyChoiceLoader.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Repository/ThirdPartyRepository.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Search/ThirdPartyApiSearch.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Search/ThirdPartyApiSearch.php
-
message: "#^Method Chill\\\\ThirdPartyBundle\\\\Search\\\\ThirdPartySearch\\:\\:renderResult\\(\\) should return string but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Search/ThirdPartySearch.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Security/Voter/ThirdPartyVoter.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
path: src/Bundle/ChillThirdPartyBundle/Templating/Entity/ThirdPartyRender.php

View File

@@ -4,7 +4,6 @@ parameters:
- src/ - src/
excludePaths: excludePaths:
- src/Bundle/*/Tests/* - src/Bundle/*/Tests/*
- src/Bundle/*/tests/*
- src/Bundle/*/Test/* - src/Bundle/*/Test/*
- src/Bundle/*/config/* - src/Bundle/*/config/*
- src/Bundle/*/migrations/* - src/Bundle/*/migrations/*
@@ -18,7 +17,5 @@ parameters:
- src/Bundle/*/src/Resources/* - src/Bundle/*/src/Resources/*
includes: includes:
- phpstan-types.neon
- phpstan-critical.neon
- phpstan-baseline.neon - phpstan-baseline.neon

View File

@@ -37,9 +37,6 @@
<testsuite name="CalendarBundle"> <testsuite name="CalendarBundle">
<directory suffix="Test.php">src/Bundle/ChillCalendarBundle/Tests/</directory> <directory suffix="Test.php">src/Bundle/ChillCalendarBundle/Tests/</directory>
</testsuite> </testsuite>
<testsuite name="DocGeneratorBundle">
<directory suffix="Test.php">src/Bundle/ChillDocGeneratorBundle/tests/</directory>
</testsuite>
</testsuites> </testsuites>
<listeners> <listeners>

View File

@@ -1,26 +1,37 @@
<?php <?php
declare(strict_types=1); /*
* 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\ActivityBundle\Controller; namespace Chill\ActivityBundle\Controller;
use Chill\ActivityBundle\Entity\ActivityReason; use Chill\ActivityBundle\Repository\ActivityACLAwareRepository;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepositoryInterface; use Chill\ActivityBundle\Repository\ActivityACLAwareRepositoryInterface;
use Chill\ActivityBundle\Repository\ActivityRepository;
use Chill\ActivityBundle\Repository\ActivityTypeCategoryRepository;
use Chill\ActivityBundle\Repository\ActivityTypeRepository;
use Chill\ActivityBundle\Security\Authorization\ActivityVoter; use Chill\ActivityBundle\Security\Authorization\ActivityVoter;
use Chill\MainBundle\Repository\LocationRepository; use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Privacy\PrivacyEvent; use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\PersonBundle\Repository\AccompanyingPeriodRepository;
use Chill\PersonBundle\Repository\PersonRepository;
use Chill\ThirdPartyBundle\Repository\ThirdPartyRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@@ -31,56 +42,33 @@ use Chill\ActivityBundle\Form\ActivityType;
use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable; use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\SerializerInterface;
final class ActivityController extends AbstractController /**
* Class ActivityController
*
* @package Chill\ActivityBundle\Controller
*/
class ActivityController extends AbstractController
{ {
private EventDispatcherInterface $eventDispatcher; protected EventDispatcherInterface $eventDispatcher;
private LoggerInterface $logger; protected AuthorizationHelper $authorizationHelper;
private SerializerInterface $serializer; protected LoggerInterface $logger;
private ActivityACLAwareRepositoryInterface $activityACLAwareRepository; protected SerializerInterface $serializer;
private ActivityTypeRepository $activityTypeRepository; protected ActivityACLAwareRepositoryInterface $activityACLAwareRepository;
private ThirdPartyRepository $thirdPartyRepository;
private PersonRepository $personRepository;
private LocationRepository $locationRepository;
private EntityManagerInterface $entityManager;
private ActivityRepository $activityRepository;
private AccompanyingPeriodRepository $accompanyingPeriodRepository;
private ActivityTypeCategoryRepository $activityTypeCategoryRepository;
public function __construct( public function __construct(
ActivityACLAwareRepositoryInterface $activityACLAwareRepository, ActivityACLAwareRepositoryInterface $activityACLAwareRepository,
ActivityTypeRepository $activityTypeRepository,
ActivityTypeCategoryRepository $activityTypeCategoryRepository,
PersonRepository $personRepository,
ThirdPartyRepository $thirdPartyRepository,
LocationRepository $locationRepository,
ActivityRepository $activityRepository,
AccompanyingPeriodRepository $accompanyingPeriodRepository,
EntityManagerInterface $entityManager,
EventDispatcherInterface $eventDispatcher, EventDispatcherInterface $eventDispatcher,
AuthorizationHelper $authorizationHelper,
LoggerInterface $logger, LoggerInterface $logger,
SerializerInterface $serializer SerializerInterface $serializer
) { ) {
$this->activityACLAwareRepository = $activityACLAwareRepository; $this->activityACLAwareRepository = $activityACLAwareRepository;
$this->activityTypeRepository = $activityTypeRepository;
$this->activityTypeCategoryRepository = $activityTypeCategoryRepository;
$this->personRepository = $personRepository;
$this->thirdPartyRepository = $thirdPartyRepository;
$this->locationRepository = $locationRepository;
$this->activityRepository = $activityRepository;
$this->accompanyingPeriodRepository = $accompanyingPeriodRepository;
$this->entityManager = $entityManager;
$this->eventDispatcher = $eventDispatcher; $this->eventDispatcher = $eventDispatcher;
$this->authorizationHelper = $authorizationHelper;
$this->logger = $logger; $this->logger = $logger;
$this->serializer = $serializer; $this->serializer = $serializer;
} }
@@ -90,8 +78,8 @@ final class ActivityController extends AbstractController
*/ */
public function listAction(Request $request): Response public function listAction(Request $request): Response
{ {
$em = $this->getDoctrine()->getManager();
$view = null; $view = null;
$activities = [];
// TODO: add pagination // TODO: add pagination
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@@ -101,10 +89,10 @@ final class ActivityController extends AbstractController
$activities = $this->activityACLAwareRepository $activities = $this->activityACLAwareRepository
->findByPerson($person, ActivityVoter::SEE, 0, null); ->findByPerson($person, ActivityVoter::SEE, 0, null);
$event = new PrivacyEvent($person, [ $event = new PrivacyEvent($person, array(
'element_class' => Activity::class, 'element_class' => Activity::class,
'action' => 'list' 'action' => 'list'
]); ));
$this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event); $this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event);
$view = 'ChillActivityBundle:Activity:listPerson.html.twig'; $view = 'ChillActivityBundle:Activity:listPerson.html.twig';
@@ -117,18 +105,16 @@ final class ActivityController extends AbstractController
$view = 'ChillActivityBundle:Activity:listAccompanyingCourse.html.twig'; $view = 'ChillActivityBundle:Activity:listAccompanyingCourse.html.twig';
} }
return $this->render( return $this->render($view, array(
$view, 'activities' => $activities,
[ 'person' => $person,
'activities' => $activities, 'accompanyingCourse' => $accompanyingPeriod,
'person' => $person, ));
'accompanyingCourse' => $accompanyingPeriod,
]
);
} }
public function selectTypeAction(Request $request): Response public function selectTypeAction(Request $request): Response
{ {
$em = $this->getDoctrine()->getManager();
$view = null; $view = null;
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@@ -141,17 +127,12 @@ final class ActivityController extends AbstractController
$data = []; $data = [];
$activityTypeCategories = $this $activityTypeCategories = $em->getRepository(\Chill\ActivityBundle\Entity\ActivityTypeCategory::class)
->activityTypeCategoryRepository
->findBy(['active' => true], ['ordering' => 'ASC']); ->findBy(['active' => true], ['ordering' => 'ASC']);
foreach ($activityTypeCategories as $activityTypeCategory) { foreach ($activityTypeCategories as $activityTypeCategory) {
$activityTypes = $this $activityTypes = $em->getRepository(\Chill\ActivityBundle\Entity\ActivityType::class)
->activityTypeRepository ->findBy(['active' => true, 'category' => $activityTypeCategory], ['ordering' => 'ASC']);
->findBy(
['active' => true, 'category' => $activityTypeCategory],
['ordering' => 'ASC']
);
$data[] = [ $data[] = [
'activityTypeCategory' => $activityTypeCategory, 'activityTypeCategory' => $activityTypeCategory,
@@ -159,6 +140,12 @@ final class ActivityController extends AbstractController
]; ];
} }
if ($request->query->has('activityData')) {
$activityData = $request->query->get('activityData');
} else {
$activityData = [];
}
if ($view === null) { if ($view === null) {
throw $this->createNotFoundException('Template not found'); throw $this->createNotFoundException('Template not found');
} }
@@ -167,13 +154,13 @@ final class ActivityController extends AbstractController
'person' => $person, 'person' => $person,
'accompanyingCourse' => $accompanyingPeriod, 'accompanyingCourse' => $accompanyingPeriod,
'data' => $data, 'data' => $data,
'activityData' => $request->query->get('activityData', []), 'activityData' => $activityData
]); ]);
} }
public function newAction(Request $request): Response public function newAction(Request $request): Response
{ {
$view = null; $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@@ -184,7 +171,8 @@ final class ActivityController extends AbstractController
} }
$activityType_id = $request->get('activityType_id', 0); $activityType_id = $request->get('activityType_id', 0);
$activityType = $this->activityTypeRepository->find($activityType_id); $activityType = $em->getRepository(\Chill\ActivityBundle\Entity\ActivityType::class)
->find($activityType_id);
if (isset($activityType) && !$activityType->isActive()) { if (isset($activityType) && !$activityType->isActive()) {
throw new \InvalidArgumentException('Activity type must be active'); throw new \InvalidArgumentException('Activity type must be active');
@@ -242,20 +230,20 @@ final class ActivityController extends AbstractController
if (array_key_exists('personsId', $activityData)) { if (array_key_exists('personsId', $activityData)) {
foreach($activityData['personsId'] as $personId){ foreach($activityData['personsId'] as $personId){
$concernedPerson = $this->personRepository->find($personId); $concernedPerson = $em->getRepository(\Chill\PersonBundle\Entity\Person::class)->find($personId);
$entity->addPerson($concernedPerson); $entity->addPerson($concernedPerson);
} }
} }
if (array_key_exists('professionalsId', $activityData)) { if (array_key_exists('professionalsId', $activityData)) {
foreach($activityData['professionalsId'] as $professionalsId){ foreach($activityData['professionalsId'] as $professionalsId){
$professional = $this->thirdPartyRepository->find($professionalsId); $professional = $em->getRepository(\Chill\ThirdPartyBundle\Entity\ThirdParty::class)->find($professionalsId);
$entity->addThirdParty($professional); $entity->addThirdParty($professional);
} }
} }
if (array_key_exists('location', $activityData)) { if (array_key_exists('location', $activityData)) {
$location = $this->locationRepository->find($activityData['location']); $location = $em->getRepository(\Chill\MainBundle\Entity\Location::class)->find($activityData['location']);
$entity->setLocation($location); $entity->setLocation($location);
} }
@@ -280,8 +268,8 @@ final class ActivityController extends AbstractController
])->handleRequest($request); ])->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($entity); $em->persist($entity);
$this->entityManager->flush(); $em->flush();
$this->addFlash('success', $this->get('translator')->trans('Success : activity created!')); $this->addFlash('success', $this->get('translator')->trans('Success : activity created!'));
@@ -309,7 +297,7 @@ final class ActivityController extends AbstractController
public function showAction(Request $request, $id): Response public function showAction(Request $request, $id): Response
{ {
$view = null; $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@@ -319,14 +307,13 @@ final class ActivityController extends AbstractController
$view = 'ChillActivityBundle:Activity:showPerson.html.twig'; $view = 'ChillActivityBundle:Activity:showPerson.html.twig';
} }
$entity = $this->activityRepository->find($id); $entity = $em->getRepository('ChillActivityBundle:Activity')->find($id);
if (null === $entity) { if (!$entity) {
throw $this->createNotFoundException('Unable to find Activity entity.'); throw $this->createNotFoundException('Unable to find Activity entity.');
} }
if (null !== $accompanyingPeriod) { if (null !== $accompanyingPeriod) {
// @TODO: Properties created dynamically.
$entity->personsAssociated = $entity->getPersonsAssociated(); $entity->personsAssociated = $entity->getPersonsAssociated();
$entity->personsNotAssociated = $entity->getPersonsNotAssociated(); $entity->personsNotAssociated = $entity->getPersonsNotAssociated();
} }
@@ -334,7 +321,7 @@ final class ActivityController extends AbstractController
// TODO revoir le Voter de Activity pour tenir compte qu'une activité peut appartenir a une période // TODO revoir le Voter de Activity pour tenir compte qu'une activité peut appartenir a une période
// $this->denyAccessUnlessGranted('CHILL_ACTIVITY_SEE', $entity); // $this->denyAccessUnlessGranted('CHILL_ACTIVITY_SEE', $entity);
$deleteForm = $this->createDeleteForm($entity->getId(), $person, $accompanyingPeriod); $deleteForm = $this->createDeleteForm($id, $person, $accompanyingPeriod);
// TODO // TODO
/* /*
@@ -350,20 +337,21 @@ final class ActivityController extends AbstractController
throw $this->createNotFoundException('Template not found'); throw $this->createNotFoundException('Template not found');
} }
return $this->render($view, [ return $this->render($view, array(
'person' => $person, 'person' => $person,
'accompanyingCourse' => $accompanyingPeriod, 'accompanyingCourse' => $accompanyingPeriod,
'entity' => $entity, 'entity' => $entity,
'delete_form' => $deleteForm->createView(), 'delete_form' => $deleteForm->createView(),
]); ));
} }
/** /**
* Displays a form to edit an existing Activity entity. * Displays a form to edit an existing Activity entity.
*
*/ */
public function editAction($id, Request $request): Response public function editAction($id, Request $request): Response
{ {
$view = null; $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@@ -373,9 +361,9 @@ final class ActivityController extends AbstractController
$view = 'ChillActivityBundle:Activity:editPerson.html.twig'; $view = 'ChillActivityBundle:Activity:editPerson.html.twig';
} }
$entity = $this->activityRepository->find($id); $entity = $em->getRepository('ChillActivityBundle:Activity')->find($id);
if (null === $entity) { if (!$entity) {
throw $this->createNotFoundException('Unable to find Activity entity.'); throw $this->createNotFoundException('Unable to find Activity entity.');
} }
@@ -390,18 +378,17 @@ final class ActivityController extends AbstractController
])->handleRequest($request); ])->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$this->entityManager->persist($entity); $em->persist($entity);
$this->entityManager->flush(); $em->flush();
$this->addFlash('success', $this->get('translator')->trans('Success : activity updated!')); $this->addFlash('success', $this->get('translator')->trans('Success : activity updated!'));
$params = $this->buildParamsToUrl($person, $accompanyingPeriod); $params = $this->buildParamsToUrl($person, $accompanyingPeriod);
$params['id'] = $entity->getId(); $params['id'] = $id;
return $this->redirectToRoute('chill_activity_activity_show', $params); return $this->redirectToRoute('chill_activity_activity_show', $params);
} }
$deleteForm = $this->createDeleteForm($entity->getId(), $person, $accompanyingPeriod); $deleteForm = $this->createDeleteForm($id, $person, $accompanyingPeriod);
/* /*
* TODO * TODO
@@ -419,22 +406,23 @@ final class ActivityController extends AbstractController
$activity_array = $this->serializer->normalize($entity, 'json', ['groups' => 'read']); $activity_array = $this->serializer->normalize($entity, 'json', ['groups' => 'read']);
return $this->render($view, [ return $this->render($view, array(
'entity' => $entity, 'entity' => $entity,
'edit_form' => $form->createView(), 'edit_form' => $form->createView(),
'delete_form' => $deleteForm->createView(), 'delete_form' => $deleteForm->createView(),
'person' => $person, 'person' => $person,
'accompanyingCourse' => $accompanyingPeriod, 'accompanyingCourse' => $accompanyingPeriod,
'activity_json' => $activity_array 'activity_json' => $activity_array
]); ));
} }
/** /**
* Deletes a Activity entity. * Deletes a Activity entity.
*
*/ */
public function deleteAction(Request $request, $id) public function deleteAction(Request $request, $id)
{ {
$view = null; $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@@ -444,7 +432,8 @@ final class ActivityController extends AbstractController
$view = 'ChillActivityBundle:Activity:confirm_deletePerson.html.twig'; $view = 'ChillActivityBundle:Activity:confirm_deletePerson.html.twig';
} }
$activity = $this->activityRepository->find($id); /* @var $activity Activity */
$activity = $em->getRepository('ChillActivityBundle:Activity')->find($id);
if (!$activity) { if (!$activity) {
throw $this->createNotFoundException('Unable to find Activity entity.'); throw $this->createNotFoundException('Unable to find Activity entity.');
@@ -453,37 +442,35 @@ final class ActivityController extends AbstractController
// TODO // TODO
// $this->denyAccessUnlessGranted('CHILL_ACTIVITY_DELETE', $activity); // $this->denyAccessUnlessGranted('CHILL_ACTIVITY_DELETE', $activity);
$form = $this->createDeleteForm($activity->getId(), $person, $accompanyingPeriod); $form = $this->createDeleteForm($id, $person, $accompanyingPeriod);
if ($request->getMethod() === Request::METHOD_DELETE) { if ($request->getMethod() === Request::METHOD_DELETE) {
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isValid()) { if ($form->isValid()) {
$this->logger->notice("An activity has been removed", [
$this->logger->notice("An activity has been removed", array(
'by_user' => $this->getUser()->getUsername(), 'by_user' => $this->getUser()->getUsername(),
'activity_id' => $activity->getId(), 'activity_id' => $activity->getId(),
'person_id' => $activity->getPerson() ? $activity->getPerson()->getId() : null, 'person_id' => $activity->getPerson() ? $activity->getPerson()->getId() : null,
'comment' => $activity->getComment()->getComment(), 'comment' => $activity->getComment()->getComment(),
'scope_id' => $activity->getScope() ? $activity->getScope()->getId() : null, 'scope_id' => $activity->getScope() ? $activity->getScope()->getId() : null,
'reasons_ids' => $activity->getReasons() 'reasons_ids' => $activity->getReasons()
->map( ->map(function ($ar) { return $ar->getId(); })
static fn (ActivityReason $ar): int => $ar->getId()
)
->toArray(), ->toArray(),
'type_id' => $activity->getType()->getId(), 'type_id' => $activity->getType()->getId(),
'duration' => $activity->getDurationTime() ? $activity->getDurationTime()->format('U') : null, 'duration' => $activity->getDurationTime() ? $activity->getDurationTime()->format('U') : null,
'date' => $activity->getDate()->format('Y-m-d'), 'date' => $activity->getDate()->format('Y-m-d'),
'attendee' => $activity->getAttendee() 'attendee' => $activity->getAttendee()
]); ));
$this->entityManager->remove($activity); $em->remove($activity);
$this->entityManager->flush(); $em->flush();
$this->addFlash('success', $this->get('translator') $this->addFlash('success', $this->get('translator')
->trans("The activity has been successfully removed.")); ->trans("The activity has been successfully removed."));
$params = $this->buildParamsToUrl($person, $accompanyingPeriod); $params = $this->buildParamsToUrl($person, $accompanyingPeriod);
return $this->redirectToRoute('chill_activity_activity_list', $params); return $this->redirectToRoute('chill_activity_activity_list', $params);
} }
} }
@@ -492,18 +479,18 @@ final class ActivityController extends AbstractController
throw $this->createNotFoundException('Template not found'); throw $this->createNotFoundException('Template not found');
} }
return $this->render($view, [ return $this->render($view, array(
'activity' => $activity, 'activity' => $activity,
'delete_form' => $form->createView(), 'delete_form' => $form->createView(),
'person' => $person, 'person' => $person,
'accompanyingCourse' => $accompanyingPeriod, 'accompanyingCourse' => $accompanyingPeriod,
]); ));
} }
/** /**
* Creates a form to delete a Activity entity by id. * Creates a form to delete a Activity entity by id.
*/ */
private function createDeleteForm(int $id, ?Person $person, ?AccompanyingPeriod $accompanyingPeriod): FormInterface private function createDeleteForm(int $id, ?Person $person, ?AccompanyingPeriod $accompanyingPeriod): Form
{ {
$params = $this->buildParamsToUrl($person, $accompanyingPeriod); $params = $this->buildParamsToUrl($person, $accompanyingPeriod);
$params['id'] = $id; $params['id'] = $id;
@@ -511,17 +498,19 @@ final class ActivityController extends AbstractController
return $this->createFormBuilder() return $this->createFormBuilder()
->setAction($this->generateUrl('chill_activity_activity_delete', $params)) ->setAction($this->generateUrl('chill_activity_activity_delete', $params))
->setMethod('DELETE') ->setMethod('DELETE')
->add('submit', SubmitType::class, ['label' => 'Delete']) ->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm(); ->getForm()
;
} }
private function getEntity(Request $request): array private function getEntity(Request $request): array
{ {
$em = $this->getDoctrine()->getManager();
$person = $accompanyingPeriod = null; $person = $accompanyingPeriod = null;
if ($request->query->has('person_id')) { if ($request->query->has('person_id')) {
$person_id = $request->get('person_id'); $person_id = $request->get('person_id');
$person = $this->personRepository->find($person_id); $person = $em->getRepository(Person::class)->find($person_id);
if ($person === null) { if ($person === null) {
throw $this->createNotFoundException('Person not found'); throw $this->createNotFoundException('Person not found');
@@ -530,7 +519,7 @@ final class ActivityController extends AbstractController
$this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person); $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person);
} elseif ($request->query->has('accompanying_period_id')) { } elseif ($request->query->has('accompanying_period_id')) {
$accompanying_period_id = $request->get('accompanying_period_id'); $accompanying_period_id = $request->get('accompanying_period_id');
$accompanyingPeriod = $this->accompanyingPeriodRepository->find($accompanying_period_id); $accompanyingPeriod = $em->getRepository(AccompanyingPeriod::class)->find($accompanying_period_id);
if ($accompanyingPeriod === null) { if ($accompanyingPeriod === null) {
throw $this->createNotFoundException('Accompanying Period not found'); throw $this->createNotFoundException('Accompanying Period not found');
@@ -543,20 +532,21 @@ final class ActivityController extends AbstractController
} }
return [ return [
$person, $person, $accompanyingPeriod
$accompanyingPeriod
]; ];
} }
private function buildParamsToUrl(?Person $person, ?AccompanyingPeriod $accompanyingPeriod): array private function buildParamsToUrl(
{ ?Person $person,
?AccompanyingPeriod $accompanyingPeriod
): array {
$params = []; $params = [];
if (null !== $person) { if ($person) {
$params['person_id'] = $person->getId(); $params['person_id'] = $person->getId();
} }
if (null !== $accompanyingPeriod) { if ($accompanyingPeriod) {
$params['accompanying_period_id'] = $accompanyingPeriod->getId(); $params['accompanying_period_id'] = $accompanyingPeriod->getId();
} }

View File

@@ -36,8 +36,6 @@ use Chill\MainBundle\DataFixtures\ORM\LoadScopes;
class LoadActivity extends AbstractFixture implements OrderedFixtureInterface class LoadActivity extends AbstractFixture implements OrderedFixtureInterface
{ {
use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
/** /**
* @var \Faker\Generator * @var \Faker\Generator
*/ */
@@ -82,10 +80,15 @@ class LoadActivity extends AbstractFixture implements OrderedFixtureInterface
* *
* @return \Chill\ActivityBundle\Entity\ActivityReason * @return \Chill\ActivityBundle\Entity\ActivityReason
*/ */
private function getRandomActivityReason() private function getRandomActivityReason(array $excludingIds)
{ {
$reasonRef = LoadActivityReason::$references[array_rand(LoadActivityReason::$references)]; $reasonRef = LoadActivityReason::$references[array_rand(LoadActivityReason::$references)];
if (in_array($this->getReference($reasonRef)->getId(), $excludingIds, true)) {
// we have a reason which should be excluded. Find another...
return $this->getRandomActivityReason($excludingIds);
}
return $this->getReference($reasonRef); return $this->getReference($reasonRef);
} }
@@ -100,7 +103,7 @@ class LoadActivity extends AbstractFixture implements OrderedFixtureInterface
return $this->getReference($userRef); return $this->getReference($userRef);
} }
public function newRandomActivity($person): ?Activity public function newRandomActivity($person)
{ {
$activity = (new Activity()) $activity = (new Activity())
->setUser($this->getRandomUser()) ->setUser($this->getRandomUser())
@@ -113,13 +116,11 @@ class LoadActivity extends AbstractFixture implements OrderedFixtureInterface
// ->setAttendee($this->faker->boolean()) // ->setAttendee($this->faker->boolean())
$usedId = array();
for ($i = 0; $i < rand(0, 4); $i++) { for ($i = 0; $i < rand(0, 4); $i++) {
$reason = $this->getRandomActivityReason(); $reason = $this->getRandomActivityReason($usedId);
if (null !== $reason) { $usedId[] = $reason->getId();
$activity->addReason($reason); $activity->addReason($reason);
} else {
return null;
}
} }
return $activity; return $activity;
@@ -136,9 +137,7 @@ class LoadActivity extends AbstractFixture implements OrderedFixtureInterface
for ($i = 0; $i < $activityNbr; $i ++) { for ($i = 0; $i < $activityNbr; $i ++) {
$activity = $this->newRandomActivity($person); $activity = $this->newRandomActivity($person);
if (null !== $activity) { $manager->persist($activity);
$manager->persist($activity);
}
} }
} }
$manager->flush(); $manager->flush();

View File

@@ -1,8 +1,27 @@
<?php <?php
/*
*
* Copyright (C) 2015, Champs Libres Cooperative SCRLFS, <http://www.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\ActivityBundle\Entity; namespace Chill\ActivityBundle\Entity;
use Chill\DocStoreBundle\Entity\Document; use Chill\DocStoreBundle\Entity\Document;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable; use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Chill\MainBundle\Entity\Location; use Chill\MainBundle\Entity\Location;
use Chill\PersonBundle\AccompanyingPeriod\SocialIssueConsistency\AccompanyingPeriodLinkedWithSocialIssuesEntityInterface; use Chill\PersonBundle\AccompanyingPeriod\SocialIssueConsistency\AccompanyingPeriodLinkedWithSocialIssuesEntityInterface;
@@ -19,7 +38,7 @@ use Chill\MainBundle\Entity\HasCenterInterface;
use Chill\MainBundle\Entity\HasScopeInterface; use Chill\MainBundle\Entity\HasScopeInterface;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface; use Chill\MainBundle\Validator\Constraints\Entity\UserCircleConsistency;
use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap; use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
@@ -183,7 +202,7 @@ class Activity implements HasCenterInterface, HasScopeInterface, AccompanyingPer
return $this->id; return $this->id;
} }
public function setUser(UserInterface $user): self public function setUser(User $user): self
{ {
$this->user = $user; $this->user = $user;

View File

@@ -1,12 +1,31 @@
<?php <?php
declare(strict_types=1); /*
*
* Copyright (C) 2015, Champs Libres Cooperative SCRLFS, <http://www.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\ActivityBundle\Entity; namespace Chill\ActivityBundle\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* Class ActivityTypeCateogry
*
* @package Chill\ActivityBundle\Entity
* @ORM\Entity() * @ORM\Entity()
* @ORM\Table(name="activitytypecategory") * @ORM\Table(name="activitytypecategory")
* @ORM\HasLifecycleCallbacks() * @ORM\HasLifecycleCallbacks()
@@ -18,7 +37,7 @@ class ActivityTypeCategory
* @ORM\Column(name="id", type="integer") * @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO") * @ORM\GeneratedValue(strategy="AUTO")
*/ */
private ?int $id = null; private ?int $id;
/** /**
* @ORM\Column(type="json") * @ORM\Column(type="json")
@@ -35,7 +54,10 @@ class ActivityTypeCategory
*/ */
private float $ordering = 0.0; private float $ordering = 0.0;
public function getId(): ?int /**
* Get id
*/
public function getId(): int
{ {
return $this->id; return $this->id;
} }

View File

@@ -1,39 +1,70 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2016 Champs-Libres <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\ActivityBundle\Export\Aggregator; namespace Chill\ActivityBundle\Export\Aggregator;
use Chill\ActivityBundle\Repository\ActivityReasonCategoryRepository;
use Chill\ActivityBundle\Repository\ActivityReasonRepository;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Export\AggregatorInterface; use Chill\MainBundle\Export\AggregatorInterface;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Doctrine\ORM\EntityRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper; use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\Query\Expr\Join;
use Chill\MainBundle\Export\ExportElementValidatedInterface; use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class ActivityReasonAggregator implements AggregatorInterface, ExportElementValidatedInterface /**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ActivityReasonAggregator implements AggregatorInterface,
ExportElementValidatedInterface
{ {
protected ActivityReasonCategoryRepository $activityReasonCategoryRepository; /**
*
* @var EntityRepository
*/
protected $categoryRepository;
protected ActivityReasonRepository $activityReasonRepository; /**
*
* @var EntityRepository
*/
protected $reasonRepository;
protected TranslatableStringHelperInterface $translatableStringHelper; /**
*
* @var TranslatableStringHelper
*/
protected $stringHelper;
public function __construct( public function __construct(
ActivityReasonCategoryRepository $activityReasonCategoryRepository, EntityRepository $categoryRepository,
ActivityReasonRepository $activityReasonRepository, EntityRepository $reasonRepository,
TranslatableStringHelper $translatableStringHelper TranslatableStringHelper $stringHelper
) { ) {
$this->activityReasonCategoryRepository = $activityReasonCategoryRepository; $this->categoryRepository = $categoryRepository;
$this->activityReasonRepository = $activityReasonRepository; $this->reasonRepository = $reasonRepository;
$this->translatableStringHelper = $translatableStringHelper; $this->stringHelper = $stringHelper;
} }
public function alterQuery(QueryBuilder $qb, $data) public function alterQuery(QueryBuilder $qb, $data)
@@ -46,7 +77,7 @@ class ActivityReasonAggregator implements AggregatorInterface, ExportElementVali
$elem = 'category.id'; $elem = 'category.id';
$alias = 'activity_categories_id'; $alias = 'activity_categories_id';
} else { } else {
throw new \RuntimeException('The data provided are not recognized.'); throw new \RuntimeException('the data provided are not recognized');
} }
$qb->addSelect($elem.' as '.$alias); $qb->addSelect($elem.' as '.$alias);
@@ -62,12 +93,11 @@ class ActivityReasonAggregator implements AggregatorInterface, ExportElementVali
(! array_key_exists('activity', $join)) (! array_key_exists('activity', $join))
) { ) {
$qb->add( $qb->add(
'join', 'join',
[ array('activity' =>
'activity' => new Join(Join::INNER_JOIN, 'activity.reasons', 'reasons') new Join(Join::INNER_JOIN, 'activity.reasons', 'reasons')
], ),
true true);
);
} }
// join category if necessary // join category if necessary
@@ -113,33 +143,28 @@ class ActivityReasonAggregator implements AggregatorInterface, ExportElementVali
public function buildForm(FormBuilderInterface $builder) public function buildForm(FormBuilderInterface $builder)
{ {
$builder->add( $builder->add('level', ChoiceType::class, array(
'level', 'choices' => array(
ChoiceType::class, 'By reason' => 'reasons',
[ 'By category of reason' => 'categories'
'choices' => [ ),
'By reason' => 'reasons', 'multiple' => false,
'By category of reason' => 'categories' 'expanded' => true,
], 'label' => 'Reason\'s level'
'multiple' => false, ));
'expanded' => true,
'label' => "Reason's level"
]
);
} }
public function validateForm($data, ExecutionContextInterface $context) public function validateForm($data, ExecutionContextInterface $context)
{ {
if ($data['level'] === null) { if ($data['level'] === null) {
$context $context->buildViolation("The reasons's level should not be empty")
->buildViolation("The reasons's level should not be empty.")
->addViolation(); ->addViolation();
} }
} }
public function getTitle() public function getTitle()
{ {
return 'Aggregate by activity reason'; return "Aggregate by activity reason";
} }
public function addRole() public function addRole()
@@ -152,33 +177,41 @@ class ActivityReasonAggregator implements AggregatorInterface, ExportElementVali
// for performance reason, we load data from db only once // for performance reason, we load data from db only once
switch ($data['level']) { switch ($data['level']) {
case 'reasons': case 'reasons':
$this->activityReasonRepository->findBy(['id' => $values]); $this->reasonRepository->findBy(array('id' => $values));
break; break;
case 'categories': case 'categories':
$this->activityReasonCategoryRepository->findBy(['id' => $values]); $this->categoryRepository->findBy(array('id' => $values));
break; break;
default: default:
throw new \RuntimeException(sprintf("The level data '%s' is invalid.", $data['level'])); throw new \RuntimeException(sprintf("the level data '%s' is invalid",
$data['level']));
} }
return function($value) use ($data) { return function($value) use ($data) {
if ($value === '_header') { if ($value === '_header') {
return $data['level'] === 'reasons' ? 'Group by reasons' : 'Group by categories of reason'; return $data['level'] === 'reasons' ?
'Group by reasons'
:
'Group by categories of reason'
;
} }
switch ($data['level']) { switch ($data['level']) {
case 'reasons': case 'reasons':
$r = $this->activityReasonRepository->find($value); /* @var $r \Chill\ActivityBundle\Entity\ActivityReason */
$r = $this->reasonRepository->find($value);
return sprintf( return $this->stringHelper->localize($r->getCategory()->getName())
"%s > %s", ." > "
$this->translatableStringHelper->localize($r->getCategory()->getName()), . $this->stringHelper->localize($r->getName());
$this->translatableStringHelper->localize($r->getName()) ;
); break;
case 'categories': case 'categories':
$c = $this->activityReasonCategoryRepository->find($value); $c = $this->categoryRepository->find($value);
return $this->translatableStringHelper->localize($c->getName()); return $this->stringHelper->localize($c->getName());
break;
// no need for a default : the default was already set above
} }
}; };
@@ -189,14 +222,12 @@ class ActivityReasonAggregator implements AggregatorInterface, ExportElementVali
// add select element // add select element
if ($data['level'] === 'reasons') { if ($data['level'] === 'reasons') {
return array('activity_reasons_id'); return array('activity_reasons_id');
} } elseif ($data['level'] === 'categories') {
if ($data['level'] === 'categories') {
return array ('activity_categories_id'); return array ('activity_categories_id');
} else {
throw new \RuntimeException('the data provided are not recognised');
} }
throw new \RuntimeException('The data provided are not recognised.');
} }
} }

View File

@@ -1,32 +1,61 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2016 Champs-Libres <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\ActivityBundle\Export\Aggregator; namespace Chill\ActivityBundle\Export\Aggregator;
use Chill\ActivityBundle\Repository\ActivityTypeRepository;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Export\AggregatorInterface; use Chill\MainBundle\Export\AggregatorInterface;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Doctrine\ORM\EntityRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\Query\Expr\Join;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ActivityTypeAggregator implements AggregatorInterface class ActivityTypeAggregator implements AggregatorInterface
{ {
protected ActivityTypeRepository $activityTypeRepository;
protected TranslatableStringHelperInterface $translatableStringHelper; /**
*
* @var EntityRepository
*/
protected $typeRepository;
public const KEY = 'activity_type_aggregator'; /**
*
* @var TranslatableStringHelper
*/
protected $stringHelper;
const KEY = 'activity_type_aggregator';
public function __construct( public function __construct(
ActivityTypeRepository $activityTypeRepository, EntityRepository $typeRepository,
TranslatableStringHelperInterface $translatableStringHelper TranslatableStringHelper $stringHelper
) { ) {
$this->activityTypeRepository = $activityTypeRepository; $this->typeRepository = $typeRepository;
$this->translatableStringHelper = $translatableStringHelper; $this->stringHelper = $stringHelper;
} }
public function alterQuery(QueryBuilder $qb, $data) public function alterQuery(QueryBuilder $qb, $data)
@@ -35,7 +64,7 @@ class ActivityTypeAggregator implements AggregatorInterface
$qb->addSelect(sprintf('IDENTITY(activity.type) AS %s', self::KEY)); $qb->addSelect(sprintf('IDENTITY(activity.type) AS %s', self::KEY));
// add the "group by" part // add the "group by" part
$qb->addGroupBy(self::KEY); $groupBy = $qb->addGroupBy(self::KEY);
} }
/** /**
@@ -68,7 +97,7 @@ class ActivityTypeAggregator implements AggregatorInterface
public function getTitle() public function getTitle()
{ {
return 'Aggregate by activity type'; return "Aggregate by activity type";
} }
public function addRole() public function addRole()
@@ -79,16 +108,17 @@ class ActivityTypeAggregator implements AggregatorInterface
public function getLabels($key, array $values, $data): \Closure public function getLabels($key, array $values, $data): \Closure
{ {
// for performance reason, we load data from db only once // for performance reason, we load data from db only once
$this->activityTypeRepository->findBy(['id' => $values]); $this->typeRepository->findBy(array('id' => $values));
return function($value): string { return function($value): string {
if ($value === '_header') { if ($value === '_header') {
return 'Activity type'; return 'Activity type';
} }
$t = $this->activityTypeRepository->find($value); /* @var $r \Chill\ActivityBundle\Entity\ActivityType */
$t = $this->typeRepository->find($value);
return $this->translatableStringHelper->localize($t->getName()); return $this->stringHelper->localize($t->getName());
}; };
} }

View File

@@ -1,24 +1,49 @@
<?php <?php
/*
* Copyright (C) 2019 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\ActivityBundle\Export\Aggregator; namespace Chill\ActivityBundle\Export\Aggregator;
use Chill\MainBundle\Repository\UserRepository;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Export\AggregatorInterface; use Chill\MainBundle\Export\AggregatorInterface;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Doctrine\ORM\Query\Expr\Join;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Doctrine\ORM\EntityManagerInterface;
use Chill\MainBundle\Entity\User;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ActivityUserAggregator implements AggregatorInterface class ActivityUserAggregator implements AggregatorInterface
{ {
public const KEY = 'activity_user_id'; /**
*
* @var EntityManagerInterface
*/
protected $em;
private UserRepository $userRepository; const KEY = 'activity_user_id';
public function __construct( function __construct(EntityManagerInterface $em)
UserRepository $userRepository {
) { $this->em = $em;
$this->userRepository = $userRepository;
} }
public function addRole() public function addRole()
@@ -48,14 +73,17 @@ class ActivityUserAggregator implements AggregatorInterface
public function getLabels($key, $values, $data): \Closure public function getLabels($key, $values, $data): \Closure
{ {
// preload users at once // preload users at once
$this->userRepository->findBy(['id' => $values]); $this->em->getRepository(User::class)
->findBy(['id' => $values]);
return function($value) { return function($value) {
if ($value === '_header') { switch ($value) {
return 'activity user'; case '_header':
return 'activity user';
default:
return $this->em->getRepository(User::class)->find($value)
->getUsername();
} }
return $this->userRepository->find($value)->getUsername();
}; };
} }
@@ -66,6 +94,6 @@ class ActivityUserAggregator implements AggregatorInterface
public function getTitle(): string public function getTitle(): string
{ {
return 'Aggregate by activity user'; return "Aggregate by activity user";
} }
} }

View File

@@ -1,40 +1,64 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2015 Champs-Libres <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\ActivityBundle\Export\Export; namespace Chill\ActivityBundle\Export\Export;
use Chill\ActivityBundle\Repository\ActivityRepository;
use Chill\MainBundle\Export\ExportInterface; use Chill\MainBundle\Export\ExportInterface;
use Chill\MainBundle\Export\FormatterInterface; use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Doctrine\ORM\Query; use Doctrine\ORM\Query;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Doctrine\ORM\EntityManagerInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class CountActivity implements ExportInterface class CountActivity implements ExportInterface
{ {
protected ActivityRepository $activityRepository; /**
*
* @var EntityManagerInterface
*/
protected $entityManager;
public function __construct( public function __construct(
ActivityRepository $activityRepository EntityManagerInterface $em
) { )
$this->activityRepository = $activityRepository; {
$this->entityManager = $em;
} }
public function buildForm(FormBuilderInterface $builder) public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder)
{ {
} }
public function getDescription() public function getDescription()
{ {
return 'Count activities by various parameters.'; return "Count activities by various parameters.";
} }
public function getTitle() public function getTitle()
{ {
return 'Count activities'; return "Count activities";
} }
public function getType() public function getType()
@@ -44,24 +68,24 @@ class CountActivity implements ExportInterface
public function initiateQuery(array $requiredModifiers, array $acl, array $data = array()) public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
{ {
$centers = array_map(static fn($el) => $el['center'], $acl); $qb = $this->entityManager->createQueryBuilder();
$centers = array_map(function($el) { return $el['center']; }, $acl);
$qb = $this $qb->select('COUNT(activity.id) as export_count_activity')
->activityRepository ->from('ChillActivityBundle:Activity', 'activity')
->createQueryBuilder('activity') ->join('activity.person', 'person')
->select('COUNT(activity.id) as export_count_activity') ;
->join('activity.person', 'person');
$qb $qb->where($qb->expr()->in('person.center', ':centers'))
->where($qb->expr()->in('person.center', ':centers')) ->setParameter('centers', $centers)
->setParameter('centers', $centers); ;
return $qb; return $qb;
} }
public function supportsModifiers() public function supportsModifiers()
{ {
return ['person', 'activity']; return array('person', 'activity');
} }
public function requiredRole() public function requiredRole()
@@ -71,7 +95,7 @@ class CountActivity implements ExportInterface
public function getAllowedFormattersTypes() public function getAllowedFormattersTypes()
{ {
return [FormatterInterface::TYPE_TABULAR]; return array(\Chill\MainBundle\Export\FormatterInterface::TYPE_TABULAR);
} }
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data)
@@ -80,12 +104,18 @@ class CountActivity implements ExportInterface
throw new \LogicException("the key $key is not used by this export"); throw new \LogicException("the key $key is not used by this export");
} }
return static fn($value) => $value === '_header' ? 'Number of activities' : $value; return function($value) {
return $value === '_header' ?
'Number of activities'
:
$value
;
};
} }
public function getQueryKeys($data) public function getQueryKeys($data)
{ {
return ['export_count_activity']; return array('export_count_activity');
} }
public function getResult($qb, $data) public function getResult($qb, $data)

View File

@@ -1,14 +1,31 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2017 Champs-Libres <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\ActivityBundle\Export\Export; namespace Chill\ActivityBundle\Export\Export;
use Chill\ActivityBundle\Repository\ActivityRepository;
use Chill\MainBundle\Export\ListInterface; use Chill\MainBundle\Export\ListInterface;
use Chill\ActivityBundle\Entity\ActivityReason; use Chill\ActivityBundle\Entity\ActivityReason;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface; use Chill\MainBundle\Entity\User;
use Doctrine\DBAL\Exception\InvalidArgumentException; use Chill\MainBundle\Entity\Scope;
use Chill\ActivityBundle\Entity\ActivityType;
use Doctrine\ORM\Query\Expr;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
@@ -20,17 +37,33 @@ use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Create a list for all activities
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ListActivity implements ListInterface class ListActivity implements ListInterface
{ {
private ActivityRepository $activityRepository;
protected EntityManagerInterface $entityManager; /**
*
* @var EntityManagerInterface
*/
protected $entityManager;
protected TranslatorInterface $translator; /**
*
* @var TranslatorInterface
*/
protected $translator;
protected TranslatableStringHelperInterface $translatableStringHelper; /**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
protected array $fields = [ protected $fields = array(
'id', 'id',
'date', 'date',
'durationTime', 'durationTime',
@@ -42,28 +75,32 @@ class ListActivity implements ListInterface
'person_firstname', 'person_firstname',
'person_lastname', 'person_lastname',
'person_id' 'person_id'
]; );
public function __construct( public function __construct(
EntityManagerInterface $em, EntityManagerInterface $em,
TranslatorInterface $translator, TranslatorInterface $translator,
TranslatableStringHelperInterface $translatableStringHelper, TranslatableStringHelper $translatableStringHelper
ActivityRepository $activityRepository )
) { {
$this->entityManager = $em; $this->entityManager = $em;
$this->translator = $translator; $this->translator = $translator;
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $translatableStringHelper;
$this->activityRepository = $activityRepository;
} }
/**
* {@inheritDoc}
*
* @param FormBuilderInterface $builder
*/
public function buildForm(FormBuilderInterface $builder) public function buildForm(FormBuilderInterface $builder)
{ {
$builder->add('fields', ChoiceType::class, [ $builder->add('fields', ChoiceType::class, array(
'multiple' => true, 'multiple' => true,
'expanded' => true, 'expanded' => true,
'choices' => array_combine($this->fields, $this->fields), 'choices' => array_combine($this->fields, $this->fields),
'label' => 'Fields to include in export', 'label' => 'Fields to include in export',
'constraints' => [new Callback([ 'constraints' => [new Callback(array(
'callback' => function($selected, ExecutionContextInterface $context) { 'callback' => function($selected, ExecutionContextInterface $context) {
if (count($selected) === 0) { if (count($selected) === 0) {
$context->buildViolation('You must select at least one element') $context->buildViolation('You must select at least one element')
@@ -71,14 +108,19 @@ class ListActivity implements ListInterface
->addViolation(); ->addViolation();
} }
} }
])] ))]
]); ));
} }
/**
* {@inheritDoc}
*
* @return type
*/
public function getAllowedFormattersTypes() public function getAllowedFormattersTypes()
{ {
return [FormatterInterface::TYPE_LIST]; return array(FormatterInterface::TYPE_LIST);
} }
public function getDescription() public function getDescription()
@@ -91,32 +133,29 @@ class ListActivity implements ListInterface
switch ($key) switch ($key)
{ {
case 'date' : case 'date' :
return static function($value) { return function($value) {
if ($value === '_header') { if ($value === '_header') return 'date';
return 'date';
}
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $value); $date = \DateTime::createFromFormat('Y-m-d H:i:s', $value);
return $date->format('d-m-Y'); return $date->format('d-m-Y');
}; };
case 'attendee': case 'attendee':
return static function($value) { return function($value) {
if ($value === '_header') { if ($value === '_header') return 'attendee';
return 'attendee';
}
return $value ? 1 : 0; return $value ? 1 : 0;
}; };
case 'list_reasons' : case 'list_reasons' :
$activityRepository = $this->activityRepository; /* @var $activityReasonsRepository EntityRepository */
$activityRepository = $this->entityManager
->getRepository('ChillActivityBundle:Activity');
return function($value) use ($activityRepository): string { return function($value) use ($activityRepository) {
if ($value === '_header') { if ($value === '_header') return 'activity reasons';
return 'activity reasons';
}
$activity = $activityRepository->find($value); $activity = $activityRepository
->find($value);
return implode(", ", array_map(function(ActivityReason $r) { return implode(", ", array_map(function(ActivityReason $r) {
@@ -129,25 +168,21 @@ class ListActivity implements ListInterface
}; };
case 'circle_name' : case 'circle_name' :
return function($value) { return function($value) {
if ($value === '_header') { if ($value === '_header') return 'circle';
return 'circle';
}
return $this->translatableStringHelper->localize(json_decode($value, true)); return $this->translatableStringHelper
->localize(json_decode($value, true));
}; };
case 'type_name' : case 'type_name' :
return function($value) { return function($value) {
if ($value === '_header') { if ($value === '_header') return 'activity type';
return 'activity type';
}
return $this->translatableStringHelper->localize(json_decode($value, true)); return $this->translatableStringHelper
->localize(json_decode($value, true));
}; };
default: default:
return static function($value) use ($key) { return function($value) use ($key) {
if ($value === '_header') { if ($value === '_header') return $key;
return $key;
}
return $value; return $value;
}; };
@@ -174,13 +209,14 @@ class ListActivity implements ListInterface
return 'activity'; return 'activity';
} }
public function initiateQuery(array $requiredModifiers, array $acl, array $data = []) public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
{ {
$centers = array_map(function($el) { return $el['center']; }, $acl); $centers = array_map(function($el) { return $el['center']; }, $acl);
// throw an error if any fields are present // throw an error if any fields are present
if (!\array_key_exists('fields', $data)) { if (!\array_key_exists('fields', $data)) {
throw new InvalidArgumentException('Any fields have been checked.'); throw new \Doctrine\DBAL\Exception\InvalidArgumentException("any fields "
. "have been checked");
} }
$qb = $this->entityManager->createQueryBuilder(); $qb = $this->entityManager->createQueryBuilder();
@@ -191,6 +227,7 @@ class ListActivity implements ListInterface
->join('person.center', 'center') ->join('person.center', 'center')
->andWhere('center IN (:authorized_centers)') ->andWhere('center IN (:authorized_centers)')
->setParameter('authorized_centers', $centers); ->setParameter('authorized_centers', $centers);
;
foreach ($this->fields as $f) { foreach ($this->fields as $f) {
if (in_array($f, $data['fields'])) { if (in_array($f, $data['fields'])) {
@@ -232,6 +269,8 @@ class ListActivity implements ListInterface
} }
} }
return $qb; return $qb;
} }
@@ -242,7 +281,7 @@ class ListActivity implements ListInterface
public function supportsModifiers() public function supportsModifiers()
{ {
return ['activity', 'person']; return array('activity', 'person');
} }
} }

View File

@@ -1,45 +1,72 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2015 Champs-Libres <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\ActivityBundle\Export\Export; namespace Chill\ActivityBundle\Export\Export;
use Chill\ActivityBundle\Repository\ActivityRepository;
use Chill\MainBundle\Export\ExportInterface; use Chill\MainBundle\Export\ExportInterface;
use Chill\MainBundle\Export\FormatterInterface; use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Doctrine\ORM\Query; use Doctrine\ORM\Query;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Doctrine\ORM\EntityManagerInterface;
/** /**
* This export allow to compute stats on activity duration. * This export allow to compute stats on activity duration.
* *
* The desired stat must be given in constructor. * The desired stat must be given in constructor.
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
class StatActivityDuration implements ExportInterface class StatActivityDuration implements ExportInterface
{ {
private ActivityRepository $activityRepository; /**
*
* @var EntityManagerInterface
*/
protected $entityManager;
public const SUM = 'sum'; const SUM = 'sum';
/** /**
* The action for this report. * The action for this report.
*
* @var string
*/ */
protected string $action; protected $action;
/** /**
* constructor
*
* @param EntityManagerInterface $em
* @param string $action the stat to perform * @param string $action the stat to perform
*/ */
public function __construct( public function __construct(
ActivityRepository $activityRepository, EntityManagerInterface $em,
string $action = 'sum' $action = 'sum'
) { )
{
$this->entityManager = $em;
$this->action = $action; $this->action = $action;
$this->activityRepository = $activityRepository;
} }
public function buildForm(FormBuilderInterface $builder) public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder)
{ {
} }
@@ -47,14 +74,14 @@ class StatActivityDuration implements ExportInterface
public function getDescription() public function getDescription()
{ {
if ($this->action === self::SUM) { if ($this->action === self::SUM) {
return 'Sum activities duration by various parameters.'; return "Sum activities duration by various parameters.";
} }
} }
public function getTitle() public function getTitle()
{ {
if ($this->action === self::SUM) { if ($this->action === self::SUM) {
return 'Sum activity duration'; return "Sum activity duration";
} }
} }
@@ -64,31 +91,29 @@ class StatActivityDuration implements ExportInterface
return 'activity'; return 'activity';
} }
public function initiateQuery(array $requiredModifiers, array $acl, array $data = []) public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
{ {
$centers = array_map( $centers = array_map(function($el) { return $el['center']; }, $acl);
static fn(array $el): string => $el['center'], $qb = $this->entityManager->createQueryBuilder();
$acl
);
$qb = $this->activityRepository->createQueryBuilder('activity');
$select = null;
if ($this->action === self::SUM) { if ($this->action === self::SUM) {
$select = 'SUM(activity.durationTime) AS export_stat_activity'; $select = "SUM(activity.durationTime) AS export_stat_activity";
} }
return $qb->select($select) $qb->select($select)
->join('activity.person', 'person') ->from('ChillActivityBundle:Activity', 'activity')
->join('person.center', 'center') ->join('activity.person', 'person')
->where($qb->expr()->in('center', ':centers')) ->join('person.center', 'center')
->setParameter(':centers', $centers); ->where($qb->expr()->in('center', ':centers'))
->setParameter(':centers', $centers)
;
return $qb;
} }
public function supportsModifiers() public function supportsModifiers()
{ {
return ['person', 'activity']; return array('person', 'activity');
} }
public function requiredRole() public function requiredRole()
@@ -98,23 +123,32 @@ class StatActivityDuration implements ExportInterface
public function getAllowedFormattersTypes() public function getAllowedFormattersTypes()
{ {
return [FormatterInterface::TYPE_TABULAR]; return array(\Chill\MainBundle\Export\FormatterInterface::TYPE_TABULAR);
} }
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data)
{ {
if ($key !== 'export_stat_activity') { if ($key !== 'export_stat_activity') {
throw new \LogicException(sprintf('The key %s is not used by this export', $key)); throw new \LogicException("the key $key is not used by this export");
} }
$header = $this->action === self::SUM ? 'Sum of activities duration' : false; switch ($this->action) {
case self::SUM:
$header = "Sum of activities duration";
}
return static fn(string $value) => $value === '_header' ? $header : $value; return function($value) use ($header) {
return $value === '_header' ?
$header
:
$value
;
};
} }
public function getQueryKeys($data) public function getQueryKeys($data)
{ {
return ['export_stat_activity']; return array('export_stat_activity');
} }
public function getResult($qb, $data) public function getResult($qb, $data)

View File

@@ -1,12 +1,25 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2017 Champs-Libres <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\ActivityBundle\Export\Filter; namespace Chill\ActivityBundle\Export\Filter;
use Chill\MainBundle\Export\FilterInterface; use Chill\MainBundle\Export\FilterInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\DateType;
@@ -15,21 +28,31 @@ use Chill\MainBundle\Form\Type\Export\FilterType;
use Doctrine\ORM\Query\Expr; use Doctrine\ORM\Query\Expr;
use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ActivityDateFilter implements FilterInterface class ActivityDateFilter implements FilterInterface
{ {
protected TranslatorInterface $translator; /**
*
* @var TranslatorInterface
*/
protected $translator;
function __construct(TranslatorInterface $translator) function __construct(TranslatorInterface $translator)
{ {
$this->translator = $translator; $this->translator = $translator;
} }
public function addRole() public function addRole()
{ {
return null; return null;
} }
public function alterQuery(QueryBuilder $qb, $data) public function alterQuery(\Doctrine\ORM\QueryBuilder $qb, $data)
{ {
$where = $qb->getDQLPart('where'); $where = $qb->getDQLPart('where');
$clause = $qb->expr()->between('activity.date', ':date_from', $clause = $qb->expr()->between('activity.date', ':date_from',
@@ -51,31 +74,23 @@ class ActivityDateFilter implements FilterInterface
return 'activity'; return 'activity';
} }
public function buildForm(FormBuilderInterface $builder) public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder)
{ {
$builder->add( $builder->add('date_from', DateType::class, array(
'date_from', 'label' => "Activities after this date",
DateType::class, 'data' => new \DateTime(),
[ 'attr' => array('class' => 'datepicker'),
'label' => 'Activities after this date', 'widget'=> 'single_text',
'data' => new \DateTime(), 'format' => 'dd-MM-yyyy',
'attr' => ['class' => 'datepicker'], ));
'widget'=> 'single_text',
'format' => 'dd-MM-yyyy',
]
);
$builder->add( $builder->add('date_to', DateType::class, array(
'date_to', 'label' => "Activities before this date",
DateType::class, 'data' => new \DateTime(),
[ 'attr' => array('class' => 'datepicker'),
'label' => 'Activities before this date', 'widget'=> 'single_text',
'data' => new \DateTime(), 'format' => 'dd-MM-yyyy',
'attr' => ['class' => 'datepicker'], ));
'widget'=> 'single_text',
'format' => 'dd-MM-yyyy',
]
);
$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) { $builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {
/* @var $filterForm \Symfony\Component\Form\FormInterface */ /* @var $filterForm \Symfony\Component\Form\FormInterface */
@@ -117,18 +132,17 @@ class ActivityDateFilter implements FilterInterface
public function describeAction($data, $format = 'string') public function describeAction($data, $format = 'string')
{ {
return [ return array(
'Filtered by date of activity: only between %date_from% and %date_to%', "Filtered by date of activity: only between %date_from% and %date_to%",
[ array(
'%date_from%' => $data['date_from']->format('d-m-Y'), "%date_from%" => $data['date_from']->format('d-m-Y'),
'%date_to%' => $data['date_to']->format('d-m-Y') '%date_to%' => $data['date_to']->format('d-m-Y')
] ));
];
} }
public function getTitle() public function getTitle()
{ {
return 'Filtered by date activity'; return "Filtered by date activity";
} }
} }

View File

@@ -1,12 +1,25 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2016 Champs-Libres <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\ActivityBundle\Export\Filter; namespace Chill\ActivityBundle\Export\Filter;
use Chill\ActivityBundle\Repository\ActivityReasonRepository;
use Chill\MainBundle\Export\FilterInterface; use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Bridge\Doctrine\Form\Type\EntityType;
@@ -15,24 +28,41 @@ use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\Query\Expr; use Doctrine\ORM\Query\Expr;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\Query\Expr\Join;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Chill\MainBundle\Export\ExportElementValidatedInterface; use Chill\MainBundle\Export\ExportElementValidatedInterface;
class ActivityReasonFilter implements FilterInterface, ExportElementValidatedInterface /**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ActivityReasonFilter implements FilterInterface,
ExportElementValidatedInterface
{ {
protected TranslatableStringHelperInterface $translatableStringHelper; /**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
protected ActivityReasonRepository $activityReasonRepository; /**
* The repository for activity reasons
*
* @var EntityRepository
*/
protected $reasonRepository;
public function __construct( public function __construct(
TranslatableStringHelper $helper, TranslatableStringHelper $helper,
ActivityReasonRepository $activityReasonRepository EntityRepository $reasonRepository
) { ) {
$this->translatableStringHelper = $helper; $this->translatableStringHelper = $helper;
$this->activityReasonRepository = $activityReasonRepository; $this->reasonRepository = $reasonRepository;
} }
public function alterQuery(QueryBuilder $qb, $data) public function alterQuery(QueryBuilder $qb, $data)
{ {
$where = $qb->getDQLPart('where'); $where = $qb->getDQLPart('where');
@@ -45,7 +75,7 @@ class ActivityReasonFilter implements FilterInterface, ExportElementValidatedInt
&& &&
!$this->checkJoinAlreadyDefined($join['activity'], 'reasons') !$this->checkJoinAlreadyDefined($join['activity'], 'reasons')
) )
|| OR
(! array_key_exists('activity', $join)) (! array_key_exists('activity', $join))
) { ) {
$qb->add( $qb->add(
@@ -71,7 +101,7 @@ class ActivityReasonFilter implements FilterInterface, ExportElementValidatedInt
* @param Join[] $joins * @param Join[] $joins
* @return boolean * @return boolean
*/ */
private function checkJoinAlreadyDefined(array $joins, $alias): bool private function checkJoinAlreadyDefined(array $joins, $alias)
{ {
foreach ($joins as $join) { foreach ($joins as $join) {
if ($join->getAlias() === $alias) { if ($join->getAlias() === $alias) {
@@ -89,25 +119,31 @@ class ActivityReasonFilter implements FilterInterface, ExportElementValidatedInt
public function buildForm(FormBuilderInterface $builder) public function buildForm(FormBuilderInterface $builder)
{ {
$builder->add('reasons', EntityType::class, [ //create a local copy of translatableStringHelper
'class' => ActivityReason::class, $helper = $this->translatableStringHelper;
'choice_label' => fn(ActivityReason $reason) => $this->translatableStringHelper->localize($reason->getName()),
'group_by' => fn(ActivityReason $reason) => $this->translatableStringHelper->localize($reason->getCategory()->getName()), $builder->add('reasons', EntityType::class, array(
'class' => 'ChillActivityBundle:ActivityReason',
'choice_label' => function (ActivityReason $reason) use ($helper) {
return $helper->localize($reason->getName());
},
'group_by' => function(ActivityReason $reason) use ($helper) {
return $helper->localize($reason->getCategory()->getName());
},
'multiple' => true, 'multiple' => true,
'expanded' => false 'expanded' => false
]); ));
} }
public function validateForm($data, ExecutionContextInterface $context) public function validateForm($data, ExecutionContextInterface $context)
{ {
if ($data['reasons'] === null || count($data['reasons']) === 0) { if ($data['reasons'] === null || count($data['reasons']) === 0) {
$context $context->buildViolation("At least one reason must be choosen")
->buildViolation('At least one reason must be chosen')
->addViolation(); ->addViolation();
} }
} }
public function getTitle() public function getTitle()
{ {
return 'Filter by reason'; return 'Filter by reason';
} }
@@ -121,15 +157,13 @@ class ActivityReasonFilter implements FilterInterface, ExportElementValidatedInt
{ {
// collect all the reasons'name used in this filter in one array // collect all the reasons'name used in this filter in one array
$reasonsNames = array_map( $reasonsNames = array_map(
fn(ActivityReason $r): string => '"' . $this->translatableStringHelper->localize($r->getName()) . '"', function(ActivityReason $r) {
$this->activityReasonRepository->findBy(array('id' => $data['reasons']->toArray())) return "\"".$this->translatableStringHelper->localize($r->getName())."\"";
); },
$this->reasonRepository->findBy(array('id' => $data['reasons']->toArray()))
);
return [ return array("Filtered by reasons: only %list%",
'Filtered by reasons: only %list%', ["%list%" => implode(", ", $reasonsNames)]);
[
'%list%' => implode(", ", $reasonsNames),
]
];
} }
} }

View File

@@ -1,37 +1,67 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2018 Champs-Libres <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\ActivityBundle\Export\Filter; namespace Chill\ActivityBundle\Export\Filter;
use Chill\ActivityBundle\Repository\ActivityTypeRepository;
use Chill\MainBundle\Export\FilterInterface; use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\Query\Expr; use Doctrine\ORM\Query\Expr;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter; use Chill\ActivityBundle\Security\Authorization\ActivityStatsVoter;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\Query\Expr\Join;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Chill\MainBundle\Export\ExportElementValidatedInterface; use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Chill\ActivityBundle\Entity\ActivityType; use Chill\ActivityBundle\Entity\ActivityType;
class ActivityTypeFilter implements FilterInterface, ExportElementValidatedInterface /**
*
*
*/
class ActivityTypeFilter implements FilterInterface,
ExportElementValidatedInterface
{ {
protected TranslatableStringHelperInterface $translatableStringHelper; /**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
protected ActivityTypeRepository $activityTypeRepository; /**
* The repository for activity reasons
*
* @var EntityRepository
*/
protected $typeRepository;
public function __construct( public function __construct(
TranslatableStringHelperInterface $translatableStringHelper, TranslatableStringHelper $helper,
ActivityTypeRepository $activityTypeRepository EntityRepository $typeRepository
) { ) {
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $helper;
$this->activityTypeRepository = $activityTypeRepository; $this->typeRepository = $typeRepository;
} }
public function alterQuery(QueryBuilder $qb, $data) public function alterQuery(QueryBuilder $qb, $data)
{ {
$where = $qb->getDQLPart('where'); $where = $qb->getDQLPart('where');
@@ -71,28 +101,28 @@ class ActivityTypeFilter implements FilterInterface, ExportElementValidatedInter
public function buildForm(FormBuilderInterface $builder) public function buildForm(FormBuilderInterface $builder)
{ {
$builder->add( //create a local copy of translatableStringHelper
'types', $helper = $this->translatableStringHelper;
EntityType::class,
[ $builder->add('types', EntityType::class, array(
'class' => ActivityType::class, 'class' => ActivityType::class,
'choice_label' => fn(ActivityType $type) => $this->translatableStringHelper->localize($type->getName()), 'choice_label' => function (ActivityType $type) use ($helper) {
'multiple' => true, return $helper->localize($type->getName());
'expanded' => false },
] 'multiple' => true,
); 'expanded' => false
));
} }
public function validateForm($data, ExecutionContextInterface $context) public function validateForm($data, ExecutionContextInterface $context)
{ {
if ($data['types'] === null || count($data['types']) === 0) { if ($data['types'] === null || count($data['types']) === 0) {
$context $context->buildViolation("At least one type must be choosen")
->buildViolation('At least one type must be chosen')
->addViolation(); ->addViolation();
} }
} }
public function getTitle() public function getTitle()
{ {
return 'Filter by activity type'; return 'Filter by activity type';
} }
@@ -106,15 +136,13 @@ class ActivityTypeFilter implements FilterInterface, ExportElementValidatedInter
{ {
// collect all the reasons'name used in this filter in one array // collect all the reasons'name used in this filter in one array
$reasonsNames = array_map( $reasonsNames = array_map(
fn(ActivityType $t): string => '"' . $this->translatableStringHelper->localize($t->getName()) . '"', function(ActivityType $t) {
$this->activityTypeRepository->findBy(['id' => $data['types']->toArray()]) return "\"".$this->translatableStringHelper->localize($t->getName())."\"";
); },
$this->typeRepository->findBy(array('id' => $data['types']->toArray()))
);
return [ return array("Filtered by activity type: only %list%",
'Filtered by activity type: only %list%', ["%list%" => implode(", ", $reasonsNames)]);
[
'%list%' => implode(", ", $reasonsNames),
]
];
} }
} }

View File

@@ -1,14 +1,25 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2017 Champs-Libres <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\ActivityBundle\Export\Filter; namespace Chill\ActivityBundle\Export\Filter;
use Chill\ActivityBundle\Repository\ActivityReasonRepository;
use Chill\MainBundle\Export\FilterInterface; use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\DateType;
@@ -18,57 +29,77 @@ use Doctrine\ORM\Query\Expr;
use Chill\MainBundle\Templating\TranslatableStringHelper; use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Chill\ActivityBundle\Entity\ActivityReason; use Chill\ActivityBundle\Entity\ActivityReason;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\EntityManager;
use Chill\PersonBundle\Export\Declarations; use Chill\PersonBundle\Export\Declarations;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Chill\MainBundle\Export\ExportElementValidatedInterface; use Chill\MainBundle\Export\ExportElementValidatedInterface;
class PersonHavingActivityBetweenDateFilter implements FilterInterface, ExportElementValidatedInterface /**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PersonHavingActivityBetweenDateFilter implements FilterInterface,
ExportElementValidatedInterface
{ {
protected TranslatableStringHelperInterface $translatableStringHelper;
protected ActivityReasonRepository $activityReasonRepository; /**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
protected TranslatorInterface $translator; /**
*
* @var EntityRepository
*/
protected $activityReasonRepository;
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct( public function __construct(
TranslatableStringHelper $translatableStringHelper, TranslatableStringHelper $translatableStringHelper,
ActivityReasonRepository $activityReasonRepository, EntityRepository $activityReasonRepository,
TranslatorInterface $translator TranslatorInterface $translator
) { ) {
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $translatableStringHelper;
$this->activityReasonRepository = $activityReasonRepository; $this->activityReasonRepository = $activityReasonRepository;
$this->translator = $translator; $this->translator = $translator;
} }
public function addRole() public function addRole()
{ {
return null; return null;
} }
public function alterQuery(QueryBuilder $qb, $data) public function alterQuery(\Doctrine\ORM\QueryBuilder $qb, $data)
{ {
// create a query for activity // create a query for activity
$sqb = $qb->getEntityManager()->createQueryBuilder(); $sqb = $qb->getEntityManager()->createQueryBuilder();
$sqb->select('person_person_having_activity.id') $sqb->select("person_person_having_activity.id")
->from('ChillActivityBundle:Activity', 'activity_person_having_activity') ->from("ChillActivityBundle:Activity", "activity_person_having_activity")
->join('activity_person_having_activity.person', 'person_person_having_activity'); ->join("activity_person_having_activity.person", "person_person_having_activity")
;
// add clause between date // add clause between date
$sqb->where('activity_person_having_activity.date BETWEEN ' $sqb->where("activity_person_having_activity.date BETWEEN "
. ':person_having_activity_between_date_from' . ":person_having_activity_between_date_from"
. ' AND ' . " AND "
. ':person_having_activity_between_date_to'); . ":person_having_activity_between_date_to");
// add clause activity reason // add clause activity reason
$sqb->join('activity_person_having_activity.reasons', 'reasons_person_having_activity'); $sqb->join('activity_person_having_activity.reasons',
'reasons_person_having_activity');
$sqb->andWhere( $sqb->andWhere(
$sqb->expr()->in( $sqb->expr()->in(
'reasons_person_having_activity', ':person_having_activity_reasons' 'reasons_person_having_activity',
) ":person_having_activity_reasons")
); );
$where = $qb->getDQLPart('where'); $where = $qb->getDQLPart('where');
$clause = $qb->expr()->in('person.id', $sqb->getDQL()); $clause = $qb->expr()->in('person.id', $sqb->getDQL());
@@ -92,36 +123,42 @@ class PersonHavingActivityBetweenDateFilter implements FilterInterface, ExportEl
return Declarations::PERSON_IMPLIED_IN; return Declarations::PERSON_IMPLIED_IN;
} }
public function buildForm(FormBuilderInterface $builder) public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder)
{ {
$builder->add('date_from', DateType::class, [ $builder->add('date_from', DateType::class, array(
'label' => 'Implied in an activity after this date', 'label' => "Implied in an activity after this date",
'data' => new \DateTime(), 'data' => new \DateTime(),
'attr' => ['class' => 'datepicker'], 'attr' => array('class' => 'datepicker'),
'widget'=> 'single_text', 'widget'=> 'single_text',
'format' => 'dd-MM-yyyy', 'format' => 'dd-MM-yyyy',
]); ));
$builder->add('date_to', DateType::class, [ $builder->add('date_to', DateType::class, array(
'label' => 'Implied in an activity before this date', 'label' => "Implied in an activity before this date",
'data' => new \DateTime(), 'data' => new \DateTime(),
'attr' => ['class' => 'datepicker'], 'attr' => array('class' => 'datepicker'),
'widget'=> 'single_text', 'widget'=> 'single_text',
'format' => 'dd-MM-yyyy', 'format' => 'dd-MM-yyyy',
]); ));
$builder->add('reasons', EntityType::class, [ $builder->add('reasons', EntityType::class, array(
'class' => ActivityReason::class, 'class' => 'ChillActivityBundle:ActivityReason',
'choice_label' => fn (ActivityReason $reason): ?string => $this->translatableStringHelper->localize($reason->getName()), 'choice_label' => function (ActivityReason $reason) {
'group_by' => fn(ActivityReason $reason): ?string => $this->translatableStringHelper->localize($reason->getCategory()->getName()), return $this->translatableStringHelper
->localize($reason->getName());
},
'group_by' => function(ActivityReason $reason) {
return $this->translatableStringHelper
->localize($reason->getCategory()->getName());
},
'data' => $this->activityReasonRepository->findAll(), 'data' => $this->activityReasonRepository->findAll(),
'multiple' => true, 'multiple' => true,
'expanded' => false, 'expanded' => false,
'label' => 'Activity reasons for those activities' 'label' => "Activity reasons for those activities"
]); ));
$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) { $builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {
/* @var FormInterface $filterForm */ /* @var $filterForm \Symfony\Component\Form\FormInterface */
$filterForm = $event->getForm()->getParent(); $filterForm = $event->getForm()->getParent();
$enabled = $filterForm->get(FilterType::ENABLED_FIELD)->getData(); $enabled = $filterForm->get(FilterType::ENABLED_FIELD)->getData();
@@ -161,33 +198,31 @@ class PersonHavingActivityBetweenDateFilter implements FilterInterface, ExportEl
public function validateForm($data, ExecutionContextInterface $context) public function validateForm($data, ExecutionContextInterface $context)
{ {
if ($data['reasons'] === null || count($data['reasons']) === 0) { if ($data['reasons'] === null || count($data['reasons']) === 0) {
$context->buildViolation('At least one reason must be chosen') $context->buildViolation("At least one reason must be choosen")
->addViolation(); ->addViolation();
} }
} }
public function describeAction($data, $format = 'string') public function describeAction($data, $format = 'string')
{ {
return [ return array(
'Filtered by person having an activity between %date_from% and ' "Filtered by person having an activity between %date_from% and "
. '%date_to% with reasons %reasons_name%', . "%date_to% with reasons %reasons_name%",
[ array(
'%date_from%' => $data['date_from']->format('d-m-Y'), "%date_from%" => $data['date_from']->format('d-m-Y'),
'%date_to%' => $data['date_to']->format('d-m-Y'), '%date_to%' => $data['date_to']->format('d-m-Y'),
'%reasons_name%' => implode( "%reasons_name%" => implode(", ", array_map(
", ", function (ActivityReason $r) {
array_map( return '"'.$this->translatableStringHelper->
fn(ActivityReason $r): string => '"' . $this->translatableStringHelper->localize($r->getName()) . '"', localize($r->getName()).'"';
$data['reasons'] },
) $data['reasons']))
) ));
]
];
} }
public function getTitle() public function getTitle()
{ {
return 'Filtered by person having an activity in a period'; return "Filtered by person having an activity in a period";
} }
} }

View File

@@ -1,29 +1,56 @@
<?php <?php
declare(strict_types=1); /*
* 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\ActivityBundle\Form\Type; namespace Chill\ActivityBundle\Form\Type;
use Chill\ActivityBundle\Repository\ActivityTypeRepository;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityRepository;
use Chill\ActivityBundle\Entity\ActivityType; use Chill\ActivityBundle\Entity\ActivityType;
/**
* Description of TranslatableActivityType
*
* @author Champs-Libres Coop
*/
class TranslatableActivityType extends AbstractType class TranslatableActivityType extends AbstractType
{ {
protected TranslatableStringHelperInterface $translatableStringHelper;
protected ActivityTypeRepository $activityTypeRepository; /**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
protected $activityTypeRepository;
public function __construct( public function __construct(
TranslatableStringHelperInterface $helper, TranslatableStringHelper $helper,
ActivityTypeRepository $activityTypeRepository EntityRepository $activityTypeRepository
) { )
{
$this->translatableStringHelper = $helper; $this->translatableStringHelper = $helper;
$this->activityTypeRepository = $activityTypeRepository; $this->activityTypeRepository = $activityTypeRepository;
} }
@@ -38,21 +65,22 @@ class TranslatableActivityType extends AbstractType
return EntityType::class; return EntityType::class;
} }
public function buildForm(FormBuilderInterface $builder, array $options) { public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder, array $options) {
/* @var QueryBuilder $qb */ /* @var $qb \Doctrine\ORM\QueryBuilder */
$qb = $options['query_builder']; $qb = $options['query_builder'];
if ($options['active_only'] === true) { if ($options['active_only'] === true) {
$qb->where($qb->expr()->eq('at.active', ':active')); $qb->where($qb->expr()->eq('at.active', ':active'));
$qb->setParameter('active', true, Types::BOOLEAN); $qb->setParameter('active', true, \Doctrine\DBAL\Types\Types::BOOLEAN);
} }
} }
public function configureOptions(OptionsResolver $resolver) public function configureOptions(OptionsResolver $resolver)
{ {
$resolver->setDefaults( $resolver->setDefaults(
array( array(
'class' => ActivityType::class, 'class' => 'ChillActivityBundle:ActivityType',
'active_only' => true, 'active_only' => true,
'query_builder' => $this->activityTypeRepository 'query_builder' => $this->activityTypeRepository
->createQueryBuilder('at'), ->createQueryBuilder('at'),

View File

@@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\ActivityBundle\Repository;
use Chill\ActivityBundle\Entity\ActivityReasonCategory;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method ActivityReasonCategory|null find($id, $lockMode = null, $lockVersion = null)
* @method ActivityReasonCategory|null findOneBy(array $criteria, array $orderBy = null)
* @method ActivityReasonCategory[] findAll()
* @method ActivityReasonCategory[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ActivityReasonCategoryRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ActivityReasonCategory::class);
}
}

View File

@@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\ActivityBundle\Repository;
use Chill\ActivityBundle\Entity\ActivityReason;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method ActivityReason|null find($id, $lockMode = null, $lockVersion = null)
* @method ActivityReason|null findOneBy(array $criteria, array $orderBy = null)
* @method ActivityReason[] findAll()
* @method ActivityReason[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ActivityReasonRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ActivityReason::class);
}
}

View File

@@ -1,6 +1,24 @@
<?php <?php
declare(strict_types=1); /*
* Chill is a software for social workers
*
* Copyright (C) 2021, 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\ActivityBundle\Repository; namespace Chill\ActivityBundle\Repository;
@@ -11,10 +29,10 @@ use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ManagerRegistry;
/** /**
* @method Activity|null find($id, $lockMode = null, $lockVersion = null) * @method AccompanyingPeriodParticipation|null find($id, $lockMode = null, $lockVersion = null)
* @method Activity|null findOneBy(array $criteria, array $orderBy = null) * @method AccompanyingPeriodParticipation|null findOneBy(array $criteria, array $orderBy = null)
* @method Activity[] findAll() * @method AccompanyingPeriodParticipation[] findAll()
* @method Activity[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) * @method AccompanyingPeriodParticipation[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/ */
class ActivityRepository extends ServiceEntityRepository class ActivityRepository extends ServiceEntityRepository
{ {
@@ -24,7 +42,12 @@ class ActivityRepository extends ServiceEntityRepository
} }
/** /**
* @return Activity[] * @param $person
* @param array $scopes
* @param string[] $orderBy
* @param int $limit
* @param int $offset
* @return array|Activity[]
*/ */
public function findByPersonImplied(Person $person, array $scopes, ?array $orderBy = [ 'date' => 'DESC'], ?int $limit = 100, ?int $offset = 0): array public function findByPersonImplied(Person $person, array $scopes, ?array $orderBy = [ 'date' => 'DESC'], ?int $limit = 100, ?int $offset = 0): array
{ {
@@ -40,7 +63,8 @@ class ActivityRepository extends ServiceEntityRepository
':person MEMBER OF a.persons' ':person MEMBER OF a.persons'
) )
) )
->setParameter('person', $person); ->setParameter('person', $person)
;
foreach ($orderBy as $k => $dir) { foreach ($orderBy as $k => $dir) {
$qb->addOrderBy('a.'.$k, $dir); $qb->addOrderBy('a.'.$k, $dir);
@@ -48,11 +72,17 @@ class ActivityRepository extends ServiceEntityRepository
$qb->setMaxResults($limit)->setFirstResult($offset); $qb->setMaxResults($limit)->setFirstResult($offset);
return $qb->getQuery()->getResult(); return $qb->getQuery()
->getResult();
} }
/** /**
* @return Activity[] * @param AccompanyingPeriod $period
* @param array $scopes
* @param int|null $limit
* @param int|null $offset
* @param array|string[] $orderBy
* @return array|Activity[]
*/ */
public function findByAccompanyingPeriod(AccompanyingPeriod $period, array $scopes, ?bool $allowNullScope = false, ?int $limit = 100, ?int $offset = 0, array $orderBy = ['date' => 'desc']): array public function findByAccompanyingPeriod(AccompanyingPeriod $period, array $scopes, ?bool $allowNullScope = false, ?int $limit = 100, ?int $offset = 0, array $orderBy = ['date' => 'desc']): array
{ {
@@ -62,7 +92,8 @@ class ActivityRepository extends ServiceEntityRepository
if (!$allowNullScope) { if (!$allowNullScope) {
$qb $qb
->where($qb->expr()->in('a.scope', ':scopes')) ->where($qb->expr()->in('a.scope', ':scopes'))
->setParameter('scopes', $scopes); ->setParameter('scopes', $scopes)
;
} else { } else {
$qb $qb
->where( ->where(
@@ -71,14 +102,16 @@ class ActivityRepository extends ServiceEntityRepository
$qb->expr()->isNull('a.scope') $qb->expr()->isNull('a.scope')
) )
) )
->setParameter('scopes', $scopes); ->setParameter('scopes', $scopes)
;
} }
$qb $qb
->andWhere( ->andWhere(
$qb->expr()->eq('a.accompanyingPeriod', ':period') $qb->expr()->eq('a.accompanyingPeriod', ':period')
) )
->setParameter('period', $period); ->setParameter('period', $period)
;
foreach ($orderBy as $k => $dir) { foreach ($orderBy as $k => $dir) {
$qb->addOrderBy('a.'.$k, $dir); $qb->addOrderBy('a.'.$k, $dir);
@@ -86,6 +119,7 @@ class ActivityRepository extends ServiceEntityRepository
$qb->setMaxResults($limit)->setFirstResult($offset); $qb->setMaxResults($limit)->setFirstResult($offset);
return $qb->getQuery()->getResult(); return $qb->getQuery()
->getResult();
} }
} }

View File

@@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\ActivityBundle\Repository;
use Chill\ActivityBundle\Entity\ActivityTypeCategory;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method ActivityTypeCategory|null find($id, $lockMode = null, $lockVersion = null)
* @method ActivityTypeCategory|null findOneBy(array $criteria, array $orderBy = null)
* @method ActivityTypeCategory[] findAll()
* @method ActivityTypeCategory[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ActivityTypeCategoryRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ActivityTypeCategory::class);
}
}

View File

@@ -1,23 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\ActivityBundle\Repository;
use Chill\ActivityBundle\Entity\ActivityType;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method ActivityType|null find($id, $lockMode = null, $lockVersion = null)
* @method ActivityType|null findOneBy(array $criteria, array $orderBy = null)
* @method ActivityType[] findAll()
* @method ActivityType[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ActivityTypeRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ActivityType::class);
}
}

View File

@@ -11,12 +11,9 @@
</div> </div>
<div v-if="getContext === 'accompanyingCourse' && filterSuggestedPersons.length > 0"> <div v-if="getContext === 'accompanyingCourse' && filterSuggestedPersons.length > 0">
<ul class="list-unstyled"> <ul>
<li v-for="p in filterSuggestedPersons" @click="addNewPerson(p)"> <li v-for="p in filterSuggestedPersons" @click="addNewPerson(p)">
<span class="badge bg-primary" style="cursor: pointer;"> {{ p.text }}
<i class="fa fa-plus fa-fw text-success"></i>
{{ p.text }}
</span>
</li> </li>
</ul> </ul>
</div> </div>

View File

@@ -4,7 +4,7 @@
<span class="chill_denomination"> <span class="chill_denomination">
{{ textCutted }} {{ textCutted }}
</span> </span>
<a class="fa fa-fw fa-times text-danger text-decoration-none" <a class="fa fa-fw fa-times"
@click.prevent="$emit('remove', person)"> @click.prevent="$emit('remove', person)">
</a> </a>
</span> </span>

View File

@@ -27,16 +27,14 @@
{{ activity.type.name | localize_translatable_string }} {{ activity.type.name | localize_translatable_string }}
<ul class="small_in_title"> <ul class="small_in_title">
{% if activity.location and t.locationVisible %}
<li> <li>
<span class="item-key">{{ 'location'|trans ~ ': ' }}</span> <abbr title="{{ 'location'|trans }}">{{ 'location'|trans ~ ': ' }}</abbr>
<span>{{ activity.location.locationType.title|localize_translatable_string }}</span> {# TODO {% if activity.location %}{{ activity.location }}{% endif %} #}
{{ activity.location.name }} Domicile de l'usager
</li> </li>
{% endif %}
{% if activity.user and t.userVisible %} {% if activity.user and t.userVisible %}
<li> <li>
<span class="item-key">{{ 'Referrer'|trans ~ ': ' }}</span> <abbr title="{{ 'Referrer'|trans }}">{{ 'Referrer'|trans ~ ': ' }}</abbr>
{{ activity.user.usernameCanonical }} {{ activity.user.usernameCanonical }}
</li> </li>
{% endif %} {% endif %}

View File

@@ -55,7 +55,7 @@
{% endif %} {% endif %}
<h2 class="chill-red">{{ 'Concerned groups'|trans }}</h2> <h2 class="chill-red">{{ 'Concerned groups'|trans }}</h2>
{% include 'ChillActivityBundle:Activity:concernedGroups.html.twig' with {'context': context, 'with_display': 'bloc', 'badge_person': 'true' } %} {% include 'ChillActivityBundle:Activity:concernedGroups.html.twig' with {'context': context, 'with_display': 'bloc' } %}
<h2 class="chill-red">{{ 'Activity data'|trans }}</h2> <h2 class="chill-red">{{ 'Activity data'|trans }}</h2>

View File

@@ -1,2 +1,4 @@
{{ dump(notification) }}
<a href="{{ path('chill_activity_activity_show', {'id': notification.relatedEntityId }) }}">Go to Activity</a> <a href="{{ path('chill_activity_activity_show', {'id': notification.relatedEntityId }) }}">Go to Activity</a>

View File

@@ -1,44 +1,85 @@
<?php <?php
declare(strict_types=1); /*
* Chill is a software for social workers
* Copyright (C) 2015 Champs Libres <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\ActivityBundle\Timeline; namespace Chill\ActivityBundle\Timeline;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface;
use Chill\MainBundle\Timeline\TimelineProviderInterface; use Chill\MainBundle\Timeline\TimelineProviderInterface;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepository; use Chill\ActivityBundle\Repository\ActivityACLAwareRepository;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManager;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Doctrine\ORM\Mapping\ClassMetadata;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\Scope;
use Chill\ActivityBundle\Entity\Activity; use Chill\ActivityBundle\Entity\Activity;
use Chill\MainBundle\Timeline\TimelineSingleQuery; use Chill\MainBundle\Timeline\TimelineSingleQuery;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Provide activity for inclusion in timeline
*
*/
class TimelineActivityProvider implements TimelineProviderInterface class TimelineActivityProvider implements TimelineProviderInterface
{ {
protected EntityManagerInterface $em;
protected AuthorizationHelperInterface $helper; /**
*
* @var EntityManager
*/
protected $em;
protected UserInterface $user; /**
*
* @var AuthorizationHelper
*/
protected $helper;
/**
*
* @var \Chill\MainBundle\Entity\User
*/
protected $user;
protected ActivityACLAwareRepository $aclAwareRepository; protected ActivityACLAwareRepository $aclAwareRepository;
private const SUPPORTED_CONTEXTS = [ 'center', 'person']; private const SUPPORTED_CONTEXTS = [ 'center', 'person'];
/**
* TimelineActivityProvider constructor.
*
* @param EntityManager $em
* @param AuthorizationHelper $helper
* @param TokenStorageInterface $storage
*/
public function __construct( public function __construct(
EntityManagerInterface $em, EntityManager $em,
AuthorizationHelperInterface $helper, AuthorizationHelper $helper,
TokenStorageInterface $storage, TokenStorageInterface $storage,
ActivityACLAwareRepository $aclAwareRepository ActivityACLAwareRepository $aclAwareRepository
) { )
{
$this->em = $em; $this->em = $em;
$this->helper = $helper; $this->helper = $helper;
$this->aclAwareRepository = $aclAwareRepository; $this->aclAwareRepository = $aclAwareRepository;
if (!$storage->getToken()->getUser() instanceof User) if (!$storage->getToken()->getUser() instanceof \Chill\MainBundle\Entity\User)
{ {
throw new \RuntimeException('A user should be authenticated !'); throw new \RuntimeException('A user should be authenticated !');
} }
@@ -67,7 +108,7 @@ class TimelineActivityProvider implements TimelineProviderInterface
'type' => 'activity', 'type' => 'activity',
'date' => $metadataActivity->getTableName() 'date' => $metadataActivity->getTableName()
.'.'.$metadataActivity->getColumnName('date'), .'.'.$metadataActivity->getColumnName('date'),
'FROM' => $this->getFromClausePerson(), 'FROM' => $this->getFromClausePerson($args['person']),
'WHERE' => $where, 'WHERE' => $where,
'parameters' => $parameters 'parameters' => $parameters
]); ]);
@@ -79,7 +120,8 @@ class TimelineActivityProvider implements TimelineProviderInterface
$metadataActivity = $this->em->getClassMetadata(Activity::class); $metadataActivity = $this->em->getClassMetadata(Activity::class);
$associationMapping = $metadataActivity->getAssociationMapping('person'); $associationMapping = $metadataActivity->getAssociationMapping('person');
$role = new Role('CHILL_ACTIVITY_SEE'); $role = new Role('CHILL_ACTIVITY_SEE');
$reachableScopes = $this->helper->getReachableScopes($this->user, $role->getRole(), $person->getCenter()); $reachableScopes = $this->helper->getReachableScopes($this->user,
$role, $person->getCenter());
$whereClause = sprintf(' {activity.person_id} = ? AND {activity.scope_id} IN ({scopes_ids}) '); $whereClause = sprintf(' {activity.person_id} = ? AND {activity.scope_id} IN ({scopes_ids}) ');
$scopes_ids = []; $scopes_ids = [];
@@ -110,23 +152,26 @@ class TimelineActivityProvider implements TimelineProviderInterface
]; ];
} }
private function getFromClausePerson(): string private function getFromClausePerson()
{ {
$metadataActivity = $this->em->getClassMetadata(Activity::class); $metadataActivity = $this->em->getClassMetadata(Activity::class);
$metadataPerson = $this->em->getClassMetadata(Person::class); $metadataPerson = $this->em->getClassMetadata(Person::class);
$associationMapping = $metadataActivity->getAssociationMapping('person'); $associationMapping = $metadataActivity->getAssociationMapping('person');
return sprintf( return $metadataActivity->getTableName().' JOIN '
"%s JOIN %s ON %s.%s = %s", .$metadataPerson->getTableName().' ON '
$metadataActivity->getTableName(), .$metadataPerson->getTableName().'.'.
$metadataPerson->getTableName(), $associationMapping['joinColumns'][0]['referencedColumnName']
$metadataPerson->getTableName(), .' = '
$associationMapping['joinColumns'][0]['referencedColumnName'], .$associationMapping['joinColumns'][0]['name']
$associationMapping['joinColumns'][0]['name'] ;
);
} }
public function getEntities(array $ids): array /**
*
* {@inheritDoc}
*/
public function getEntities(array $ids)
{ {
$activities = $this->em->getRepository(Activity::class) $activities = $this->em->getRepository(Activity::class)
->findBy(array('id' => $ids)); ->findBy(array('id' => $ids));
@@ -139,7 +184,11 @@ class TimelineActivityProvider implements TimelineProviderInterface
return $result; return $result;
} }
public function getEntityTemplate($entity, $context, array $args): array /**
*
* {@inheritDoc}
*/
public function getEntityTemplate($entity, $context, array $args)
{ {
$this->checkContext($context); $this->checkContext($context);
@@ -152,25 +201,26 @@ class TimelineActivityProvider implements TimelineProviderInterface
]; ];
} }
public function supportsType($type): bool /**
*
* {@inheritDoc}
*/
public function supportsType($type)
{ {
return $type === 'activity'; return $type === 'activity';
} }
/** /**
* Check if the context is supported. * check if the context is supported
* *
* @param string $context
* @throws \LogicException if the context is not supported * @throws \LogicException if the context is not supported
*/ */
private function checkContext(string $context) private function checkContext($context)
{ {
if (FALSE === \in_array($context, self::SUPPORTED_CONTEXTS)) { if (FALSE === \in_array($context, self::SUPPORTED_CONTEXTS)) {
throw new \LogicException( throw new \LogicException("The context '$context' is not "
sprintf( . "supported. Currently only 'person' is supported");
"The context '%s' is not supported. Currently only 'person' is supported",
$context
)
);
} }
} }

View File

@@ -1,7 +1,4 @@
services: services:
_defaults:
autowire: true
autoconfigure: true
chill.activity.timeline: chill.activity.timeline:
class: Chill\ActivityBundle\Timeline\TimelineActivityProvider class: Chill\ActivityBundle\Timeline\TimelineActivityProvider
@@ -16,14 +13,17 @@ services:
- { name: chill.timeline, context: 'center' } - { name: chill.timeline, context: 'center' }
Chill\ActivityBundle\Menu\: Chill\ActivityBundle\Menu\:
autowire: true
autoconfigure: true
resource: '../Menu/' resource: '../Menu/'
tags: ['chill.menu_builder'] tags: ['chill.menu_builder']
Chill\ActivityBundle\Notification\: Chill\ActivityBundle\Notification\:
autowire: true
autoconfigure: true
resource: '../Notification' resource: '../Notification'
Chill\ActivityBundle\Security\Authorization\: Chill\ActivityBundle\Security\Authorization\:
resource: '../Security/Authorization/' resource: '../Security/Authorization/'
autowire: true
Chill\ActivityBundle\Repository\: autoconfigure: true
resource: '../Repository/'

View File

@@ -1,40 +1,57 @@
services: services:
_defaults:
autowire: true
autoconfigure: true
chill.activity.export.count_activity: chill.activity.export.count_activity:
class: Chill\ActivityBundle\Export\Export\CountActivity class: Chill\ActivityBundle\Export\Export\CountActivity
arguments:
- "@doctrine.orm.entity_manager"
tags: tags:
- { name: chill.export, alias: 'count_activity' } - { name: chill.export, alias: 'count_activity' }
chill.activity.export.sum_activity_duration: chill.activity.export.sum_activity_duration:
class: Chill\ActivityBundle\Export\Export\StatActivityDuration class: Chill\ActivityBundle\Export\Export\StatActivityDuration
arguments:
- "@doctrine.orm.entity_manager"
- "sum"
tags: tags:
- { name: chill.export, alias: 'sum_activity_duration' } - { name: chill.export, alias: 'sum_activity_duration' }
chill.activity.export.list_activity: chill.activity.export.list_activity:
class: Chill\ActivityBundle\Export\Export\ListActivity class: Chill\ActivityBundle\Export\Export\ListActivity
arguments:
- "@doctrine.orm.entity_manager"
- "@translator"
- "@chill.main.helper.translatable_string"
tags: tags:
- { name: chill.export, alias: 'list_activity' } - { name: chill.export, alias: 'list_activity' }
chill.activity.export.reason_filter: chill.activity.export.reason_filter:
class: Chill\ActivityBundle\Export\Filter\ActivityReasonFilter class: Chill\ActivityBundle\Export\Filter\ActivityReasonFilter
arguments:
- "@chill.main.helper.translatable_string"
- "@chill_activity.repository.reason"
tags: tags:
- { name: chill.export_filter, alias: 'activity_reason_filter' } - { name: chill.export_filter, alias: 'activity_reason_filter' }
chill.activity.export.type_filter: chill.activity.export.type_filter:
class: Chill\ActivityBundle\Export\Filter\ActivityTypeFilter class: Chill\ActivityBundle\Export\Filter\ActivityTypeFilter
arguments:
- "@chill.main.helper.translatable_string"
- "@chill_activity.repository.activity_type"
tags: tags:
- { name: chill.export_filter, alias: 'activity_type_filter' } - { name: chill.export_filter, alias: 'activity_type_filter' }
chill.activity.export.date_filter: chill.activity.export.date_filter:
class: Chill\ActivityBundle\Export\Filter\ActivityDateFilter class: Chill\ActivityBundle\Export\Filter\ActivityDateFilter
arguments:
- "@translator"
tags: tags:
- { name: chill.export_filter, alias: 'activity_date_filter' } - { name: chill.export_filter, alias: 'activity_date_filter' }
chill.activity.export.person_having_an_activity_between_date_filter: chill.activity.export.person_having_an_activity_between_date_filter:
class: Chill\ActivityBundle\Export\Filter\PersonHavingActivityBetweenDateFilter class: Chill\ActivityBundle\Export\Filter\PersonHavingActivityBetweenDateFilter
arguments:
- "@chill.main.helper.translatable_string"
- "@chill_activity.repository.reason"
- "@translator"
tags: tags:
- #0 register as a filter - #0 register as a filter
name: chill.export_filter name: chill.export_filter
@@ -42,15 +59,24 @@ services:
chill.activity.export.reason_aggregator: chill.activity.export.reason_aggregator:
class: Chill\ActivityBundle\Export\Aggregator\ActivityReasonAggregator class: Chill\ActivityBundle\Export\Aggregator\ActivityReasonAggregator
arguments:
- "@chill_activity.repository.reason_category"
- "@chill_activity.repository.reason"
- "@chill.main.helper.translatable_string"
tags: tags:
- { name: chill.export_aggregator, alias: activity_reason_aggregator } - { name: chill.export_aggregator, alias: activity_reason_aggregator }
chill.activity.export.type_aggregator: chill.activity.export.type_aggregator:
class: Chill\ActivityBundle\Export\Aggregator\ActivityTypeAggregator class: Chill\ActivityBundle\Export\Aggregator\ActivityTypeAggregator
arguments:
- "@chill_activity.repository.activity_type"
- "@chill.main.helper.translatable_string"
tags: tags:
- { name: chill.export_aggregator, alias: activity_type_aggregator } - { name: chill.export_aggregator, alias: activity_type_aggregator }
chill.activity.export.user_aggregator: chill.activity.export.user_aggregator:
class: Chill\ActivityBundle\Export\Aggregator\ActivityUserAggregator class: Chill\ActivityBundle\Export\Aggregator\ActivityUserAggregator
arguments:
$em: "@doctrine.orm.entity_manager"
tags: tags:
- { name: chill.export_aggregator, alias: activity_user_aggregator } - { name: chill.export_aggregator, alias: activity_user_aggregator }

View File

@@ -1,12 +1,28 @@
--- ---
services: services:
chill_activity.repository.activity_type: '@Chill\ActivityBundle\Repository\ActivityTypeRepository' chill_activity.repository.activity_type:
chill_activity.repository.reason: '@Chill\ActivityBundle\Repository\ActivityReasonRepository' class: Doctrine\ORM\EntityRepository
chill_activity.repository.reason_category: '@Chill\ActivityBundle\Repository\ActivityReasonCategoryRepository' factory: ['@doctrine.orm.entity_manager', getRepository]
arguments:
- 'Chill\ActivityBundle\Entity\ActivityType'
chill_activity.repository.reason:
class: Doctrine\ORM\EntityRepository
factory: ['@doctrine.orm.entity_manager', getRepository]
arguments:
- 'Chill\ActivityBundle\Entity\ActivityReason'
chill_activity.repository.reason_category:
class: Doctrine\ORM\EntityRepository
factory: ['@doctrine.orm.entity_manager', getRepository]
arguments:
- 'Chill\ActivityBundle\Entity\ActivityReasonCategory'
Chill\ActivityBundle\Repository\ActivityRepository:
tags: [doctrine.repository_service]
arguments:
- '@Doctrine\Persistence\ManagerRegistry'
# This is not a repository but merely a service. It needs to be moved out for simplicity.
# The autowire and autoconfigure should be enabled globally and removed from the definition of the service.
# Once autoloaded, there is no need to alias it to the interface here, it will be done automatically by Symfony.
Chill\ActivityBundle\Repository\ActivityACLAwareRepository: Chill\ActivityBundle\Repository\ActivityACLAwareRepository:
autowire: true autowire: true
autoconfigure: true autoconfigure: true

View File

@@ -1,33 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\Migrations\Activity;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20211119173555 extends AbstractMigration
{
public function getDescription(): string
{
return 'remove comment on deprecated json_array type';
}
public function up(Schema $schema): void
{
$columns = [
'activitytype.name',
'activitytypecategory.name'
];
foreach ($columns as $col) {
$this->addSql("COMMENT ON COLUMN $col IS NULL");
}
}
public function down(Schema $schema): void
{
$this->throwIrreversibleMigrationException();
}
}

View File

@@ -15,7 +15,8 @@ use Doctrine\Common\Collections\Criteria;
final class AsideActivityController extends CRUDController final class AsideActivityController extends CRUDController
{ {
private AsideActivityCategoryRepository $categoryRepository;
private $categoryRepository;
public function __construct(AsideActivityCategoryRepository $categoryRepository) public function __construct(AsideActivityCategoryRepository $categoryRepository)
{ {
@@ -24,7 +25,7 @@ final class AsideActivityController extends CRUDController
protected function buildQueryEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null) protected function buildQueryEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null)
{ {
$qb = parent::buildQueryEntities($action, $request); $qb = parent::buildQueryEntities($action, $request, $filterOrder);
if ('index' === $action) { if ('index' === $action) {
$qb->where($qb->expr()->eq('e.agent', ':user')); $qb->where($qb->expr()->eq('e.agent', ':user'));

View File

@@ -44,15 +44,13 @@ class AsideActivityCategory
* @ORM\ManyToOne(targetEntity=AsideActivityCategory::class, inversedBy="children") * @ORM\ManyToOne(targetEntity=AsideActivityCategory::class, inversedBy="children")
* @ORM\JoinColumn(nullable=true) * @ORM\JoinColumn(nullable=true)
*/ */
private ?AsideActivityCategory $parent = null; private $parent;
/** /**
* @ORM\OneToMany(targetEntity=AsideActivityCategory::class, mappedBy="parent") * @ORM\OneToMany(targetEntity=AsideActivityCategory::class, mappedBy="parent")
*/ */
private $children; private $children;
private AsideActivityCategory $oldParent;
public function __construct() public function __construct()
{ {
$this->children = new ArrayCollection(); $this->children = new ArrayCollection();

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\AsideActivityBundle\Form; namespace Chill\AsideActivityBundle\Form;
use Chill\AsideActivityBundle\Entity\AsideActivityCategory; use Chill\AsideActivityBundle\Entity\AsideActivityCategory;
@@ -16,11 +14,12 @@ use Symfony\Component\Form\FormBuilderInterface;
final class AsideActivityCategoryType extends AbstractType final class AsideActivityCategoryType extends AbstractType
{ {
private CategoryRender $categoryRender;
public function __construct( protected $translatableStringHelper;
CategoryRender $categoryRender
) { public function __construct(TranslatableStringHelper $translatableStringHelper, CategoryRender $categoryRender)
{
$this->translatableStringHelper = $translatableStringHelper;
$this->categoryRender = $categoryRender; $this->categoryRender = $categoryRender;
} }

View File

@@ -25,16 +25,18 @@ use Symfony\Component\Templating\EngineInterface;
final class AsideActivityFormType extends AbstractType final class AsideActivityFormType extends AbstractType
{ {
private array $timeChoices; protected array $timeChoices;
private TokenStorageInterface $storage; private TokenStorageInterface $storage;
private CategoryRender $categoryRender; private CategoryRender $categoryRender;
public function __construct ( public function __construct (
TranslatableStringHelper $translatableStringHelper,
ParameterBagInterface $parameterBag, ParameterBagInterface $parameterBag,
TokenStorageInterface $storage, TokenStorageInterface $storage,
CategoryRender $categoryRender CategoryRender $categoryRender
){ ){
$this->timeChoices = $parameterBag->get('chill_aside_activity.form.time_duration'); $this->timeChoices = $parameterBag->get('chill_aside_activity.form.time_duration');
$this->translatableStringHelper = $translatableStringHelper;
$this->storage = $storage; $this->storage = $storage;
$this->categoryRender = $categoryRender; $this->categoryRender = $categoryRender;
} }

View File

@@ -1,34 +1,42 @@
<?php <?php
declare(strict_types=1);
namespace Chill\AMLI\BudgetBundle\Form; namespace Chill\AMLI\BudgetBundle\Form;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Chill\MainBundle\Form\Type\ChillDateType; use Chill\MainBundle\Form\Type\ChillDateType;
use Chill\AMLI\BudgetBundle\Config\ConfigRepository; use Chill\AMLI\BudgetBundle\Config\ConfigRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\AMLI\BudgetBundle\Entity\Charge; use Chill\AMLI\BudgetBundle\Entity\Charge;
class ChargeType extends AbstractType class ChargeType extends AbstractType
{ {
protected ConfigRepository $configRepository; /**
*
* @var ConfigRepository
*/
protected $configRepository;
protected TranslatableStringHelperInterface $translatableStringHelper; /**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
public function __construct( public function __construct(
ConfigRepository $configRepository, ConfigRepository $configRepository,
TranslatableStringHelperInterface $translatableStringHelper TranslatableStringHelper $translatableStringHelper
) { ) {
$this->configRepository = $configRepository; $this->configRepository = $configRepository;
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $translatableStringHelper;
} }
public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
$builder $builder
@@ -37,9 +45,10 @@ class ChargeType extends AbstractType
'placeholder' => 'Choose a charge type' 'placeholder' => 'Choose a charge type'
]) ])
->add('amount', MoneyType::class) ->add('amount', MoneyType::class)
->add('comment', TextareaType::class, [ ->add('comment', TextAreaType::class, [
'required' => false 'required' => false
]); ])
;
if ($options['show_start_date']) { if ($options['show_start_date']) {
$builder->add('startDate', ChillDateType::class, [ $builder->add('startDate', ChillDateType::class, [
@@ -84,10 +93,13 @@ class ChargeType extends AbstractType
return \array_flip($charges); return \array_flip($charges);
} }
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver) public function configureOptions(OptionsResolver $resolver)
{ {
$resolver->setDefaults(array( $resolver->setDefaults(array(
'data_class' => Charge::class, 'data_class' => 'Chill\AMLI\BudgetBundle\Entity\Charge',
'show_start_date' => true, 'show_start_date' => true,
'show_end_date' => true, 'show_end_date' => true,
'show_help' => true 'show_help' => true
@@ -96,11 +108,17 @@ class ChargeType extends AbstractType
$resolver $resolver
->setAllowedTypes('show_start_date', 'boolean') ->setAllowedTypes('show_start_date', 'boolean')
->setAllowedTypes('show_end_date', 'boolean') ->setAllowedTypes('show_end_date', 'boolean')
->setAllowedTypes('show_help', 'boolean'); ->setAllowedTypes('show_help', 'boolean')
;
} }
/**
* {@inheritdoc}
*/
public function getBlockPrefix() public function getBlockPrefix()
{ {
return 'chill_amli_budgetbundle_charge'; return 'chill_amli_budgetbundle_charge';
} }
} }

View File

@@ -1,10 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Chill\AMLI\BudgetBundle\Form; namespace Chill\AMLI\BudgetBundle\Form;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
@@ -13,22 +10,32 @@ use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Chill\MainBundle\Form\Type\ChillDateType; use Chill\MainBundle\Form\Type\ChillDateType;
use Chill\AMLI\BudgetBundle\Config\ConfigRepository; use Chill\AMLI\BudgetBundle\Config\ConfigRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextareaType;
class ResourceType extends AbstractType class ResourceType extends AbstractType
{ {
protected ConfigRepository $configRepository; /**
*
* @var ConfigRepository
*/
protected $configRepository;
protected TranslatableStringHelperInterface $translatableStringHelper; /**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
public function __construct( public function __construct(
ConfigRepository $configRepository, ConfigRepository $configRepository,
TranslatableStringHelperInterface $translatableStringHelper TranslatableStringHelper $translatableStringHelper
) { ) {
$this->configRepository = $configRepository; $this->configRepository = $configRepository;
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $translatableStringHelper;
} }
public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
$builder $builder
@@ -38,9 +45,10 @@ class ResourceType extends AbstractType
'label' => 'Resource element type' 'label' => 'Resource element type'
]) ])
->add('amount', MoneyType::class) ->add('amount', MoneyType::class)
->add('comment', TextareaType::class, [ ->add('comment', TextAreaType::class, [
'required' => false 'required' => false
]); ])
;
if ($options['show_start_date']) { if ($options['show_start_date']) {
$builder->add('startDate', ChillDateType::class, [ $builder->add('startDate', ChillDateType::class, [
@@ -56,24 +64,6 @@ class ResourceType extends AbstractType
} }
} }
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Resource::class,
'show_start_date' => true,
'show_end_date' => true
));
$resolver
->setAllowedTypes('show_start_date', 'boolean')
->setAllowedTypes('show_end_date', 'boolean');
}
public function getBlockPrefix()
{
return 'chill_amli_budgetbundle_resource';
}
private function getTypes() private function getTypes()
{ {
$resources = $this->configRepository $resources = $this->configRepository
@@ -88,4 +78,31 @@ class ResourceType extends AbstractType
return \array_flip($resources); return \array_flip($resources);
} }
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Resource::class,
'show_start_date' => true,
'show_end_date' => true
));
$resolver
->setAllowedTypes('show_start_date', 'boolean')
->setAllowedTypes('show_end_date', 'boolean')
;
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'chill_amli_budgetbundle_resource';
}
} }

View File

@@ -1,6 +1,24 @@
<?php <?php
declare(strict_types=1); /*
* 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\CalendarBundle\Controller; namespace Chill\CalendarBundle\Controller;
@@ -8,11 +26,9 @@ use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Privacy\PrivacyEvent; use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Form; use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@@ -26,6 +42,11 @@ use Chill\MainBundle\Pagination\PaginatorFactory;
use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
/**
* Class CalendarController
*
* @package Chill\CalendarBundle\Controller
*/
class CalendarController extends AbstractController class CalendarController extends AbstractController
{ {
protected EventDispatcherInterface $eventDispatcher; protected EventDispatcherInterface $eventDispatcher;
@@ -106,7 +127,6 @@ class CalendarController extends AbstractController
*/ */
public function newAction(Request $request): Response public function newAction(Request $request): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@@ -143,12 +163,11 @@ class CalendarController extends AbstractController
$params = $this->buildParamsToUrl($user, $accompanyingPeriod); $params = $this->buildParamsToUrl($user, $accompanyingPeriod);
return $this->redirectToRoute('chill_calendar_calendar_list', $params); return $this->redirectToRoute('chill_calendar_calendar_list', $params);
} } elseif ($form->isSubmitted() and !$form->isValid()) {
if ($form->isSubmitted() and !$form->isValid()) {
$this->addFlash('error', $this->get('translator')->trans('This form contains errors')); $this->addFlash('error', $this->get('translator')->trans('This form contains errors'));
} }
if ($view === null) { if ($view === null) {
throw $this->createNotFoundException('Template not found'); throw $this->createNotFoundException('Template not found');
} }
@@ -170,7 +189,6 @@ class CalendarController extends AbstractController
*/ */
public function showAction(Request $request, $id): Response public function showAction(Request $request, $id): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@@ -182,36 +200,32 @@ class CalendarController extends AbstractController
$view = '@ChillCalendar/Calendar/showByUser.html.twig'; $view = '@ChillCalendar/Calendar/showByUser.html.twig';
} }
if ($view === null) {
throw $this->createNotFoundException('Template not found');
}
/** @var Calendar $entity */
$entity = $em->getRepository('ChillCalendarBundle:Calendar')->find($id); $entity = $em->getRepository('ChillCalendarBundle:Calendar')->find($id);
if (null === $entity) { if (!$entity) {
throw $this->createNotFoundException('Unable to find Calendar entity.'); throw $this->createNotFoundException('Unable to find Calendar entity.');
} }
if (null !== $accompanyingPeriod) { if (null !== $accompanyingPeriod) {
// @TODO: These properties are declared dynamically. $entity->personsAssociated = $entity->getPersonsAssociated();
// It must be removed. $entity->personsNotAssociated = $entity->getPersonsNotAssociated();
// @See https://wiki.php.net/rfc/deprecate_dynamic_properties
$entity->personsAssociated = $entity->getPersonsAssociated();
$entity->personsNotAssociated = $entity->getPersonsNotAssociated();
} }
// $deleteForm = $this->createDeleteForm($id, $accompanyingPeriod); // $deleteForm = $this->createDeleteForm($id, $accompanyingPeriod);
$personsId = array_map( if ($view === null) {
static fn (Person $p): int => $p->getId(), throw $this->createNotFoundException('Template not found');
$entity->getPersons() }
);
$professionalsId = array_map( $personsId = [];
static fn (ThirdParty $thirdParty): ?int => $thirdParty->getId(), foreach ($entity->getPersons() as $p) {
$entity->getProfessionals() array_push($personsId, $p->getId());
); }
$professionalsId = [];
foreach ($entity->getProfessionals() as $p) {
array_push($professionalsId, $p->getId());
}
$durationTime = $entity->getEndDate()->diff($entity->getStartDate()); $durationTime = $entity->getEndDate()->diff($entity->getStartDate());
$durationTimeInMinutes = $durationTime->days*1440 + $durationTime->h*60 + $durationTime->i; $durationTimeInMinutes = $durationTime->days*1440 + $durationTime->h*60 + $durationTime->i;
@@ -228,7 +242,7 @@ class CalendarController extends AbstractController
return $this->render($view, [ return $this->render($view, [
'accompanyingCourse' => $accompanyingPeriod, 'accompanyingCourse' => $accompanyingPeriod,
'entity' => $entity, 'entity' => $entity,
'user' => $user, 'user' => $user,
'activityData' => $activityData 'activityData' => $activityData
//'delete_form' => $deleteForm->createView(), //'delete_form' => $deleteForm->createView(),
@@ -243,7 +257,6 @@ class CalendarController extends AbstractController
*/ */
public function editAction($id, Request $request): Response public function editAction($id, Request $request): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@@ -272,11 +285,8 @@ class CalendarController extends AbstractController
$this->addFlash('success', $this->get('translator')->trans('Success : calendar item updated!')); $this->addFlash('success', $this->get('translator')->trans('Success : calendar item updated!'));
$params = $this->buildParamsToUrl($user, $accompanyingPeriod); $params = $this->buildParamsToUrl($user, $accompanyingPeriod);
return $this->redirectToRoute('chill_calendar_calendar_list', $params); return $this->redirectToRoute('chill_calendar_calendar_list', $params);
} } elseif ($form->isSubmitted() and !$form->isValid()) {
if ($form->isSubmitted() and !$form->isValid()) {
$this->addFlash('error', $this->get('translator')->trans('This form contains errors')); $this->addFlash('error', $this->get('translator')->trans('This form contains errors'));
} }
@@ -304,7 +314,6 @@ class CalendarController extends AbstractController
*/ */
public function deleteAction(Request $request, $id) public function deleteAction(Request $request, $id)
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@@ -360,7 +369,7 @@ class CalendarController extends AbstractController
/** /**
* Creates a form to delete a Calendar entity by id. * Creates a form to delete a Calendar entity by id.
*/ */
private function createDeleteForm(int $id, ?User $user, ?AccompanyingPeriod $accompanyingPeriod): FormInterface private function createDeleteForm(int $id, ?User $user, ?AccompanyingPeriod $accompanyingPeriod): Form
{ {
$params = $this->buildParamsToUrl($user, $accompanyingPeriod); $params = $this->buildParamsToUrl($user, $accompanyingPeriod);
$params['id'] = $id; $params['id'] = $id;
@@ -407,14 +416,17 @@ class CalendarController extends AbstractController
]; ];
} }
private function buildParamsToUrl(?User $user, ?AccompanyingPeriod $accompanyingPeriod): array { private function buildParamsToUrl(
?User $user,
?AccompanyingPeriod $accompanyingPeriod
): array {
$params = []; $params = [];
if (null !== $user) { if ($user) {
$params['user_id'] = $user->getId(); $params['user_id'] = $user->getId();
} }
if (null !== $accompanyingPeriod) { if ($accompanyingPeriod) {
$params['accompanying_period_id'] = $accompanyingPeriod->getId(); $params['accompanying_period_id'] = $accompanyingPeriod->getId();
} }

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\CalendarBundle\DataFixtures\ORM; namespace Chill\CalendarBundle\DataFixtures\ORM;
use Chill\CalendarBundle\Entity\CalendarRange; use Chill\CalendarBundle\Entity\CalendarRange;
@@ -17,10 +15,6 @@ use Doctrine\Persistence\ObjectManager;
class LoadCalendarRange extends Fixture implements FixtureGroupInterface, OrderedFixtureInterface class LoadCalendarRange extends Fixture implements FixtureGroupInterface, OrderedFixtureInterface
{ {
private UserRepository $userRepository;
public static array $references = [];
public function __construct( public function __construct(
UserRepository $userRepository UserRepository $userRepository
) { ) {
@@ -37,6 +31,8 @@ class LoadCalendarRange extends Fixture implements FixtureGroupInterface, Ordere
return ['calendar']; return ['calendar'];
} }
public static $references = [];
public function load(ObjectManager $manager): void public function load(ObjectManager $manager): void
{ {
$arr = range(-50, 50); $arr = range(-50, 50);

View File

@@ -1,33 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\Migrations\Calendar;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20211119173557 extends AbstractMigration
{
public function getDescription(): string
{
return 'remove comment on deprecated json_array type';
}
public function up(Schema $schema): void
{
$columns = [
'chill_calendar.cancel_reason.name',
'chill_calendar.invite.status',
];
foreach ($columns as $col) {
$this->addSql("COMMENT ON COLUMN $col IS NULL");
}
}
public function down(Schema $schema): void
{
$this->throwIrreversibleMigrationException();
}
}

View File

@@ -151,7 +151,8 @@ class CreateFieldsOnGroupCommand extends Command
return $customFieldsGroup; return $customFieldsGroup;
} }
} }
throw new \RuntimeException('The id does not match an existing CustomFieldsGroup'); throw new \RunTimeException('The id does not match an existing '
. 'CustomFieldsGroup');
} }
); );
$customFieldsGroup = $helper->ask($input, $output, $question); $customFieldsGroup = $helper->ask($input, $output, $question);
@@ -204,13 +205,13 @@ class CreateFieldsOnGroupCommand extends Command
$parser = new Parser(); $parser = new Parser();
if (!file_exists($path)) { if (!file_exists($path)) {
throw new \RuntimeException("file does not exist"); throw new \RunTimeException("file does not exist");
} }
try { try {
$values = $parser->parse(file_get_contents($path)); $values = $parser->parse(file_get_contents($path));
} catch (ParseException $ex) { } catch (ParseException $ex) {
throw new \RuntimeException("The yaml file is not valid", 0, $ex); throw new \RunTimeException("The yaml file is not valid", 0, $ex);
} }
return $values; return $values;
@@ -227,7 +228,7 @@ class CreateFieldsOnGroupCommand extends Command
//check the cf type exists //check the cf type exists
$cfType = $this->customFieldProvider->getCustomFieldByType($field['type']); $cfType = $this->customFieldProvider->getCustomFieldByType($field['type']);
if ($cfType === NULL) { if ($cfType === NULL) {
throw new \RuntimeException('the type '.$field['type'].' ' throw new \RunTimeException('the type '.$field['type'].' '
. 'does not exists'); . 'does not exists');
} }
@@ -254,7 +255,7 @@ class CreateFieldsOnGroupCommand extends Command
.$cf->getType()."\t with slug ".$cf->getSlug(). .$cf->getType()."\t with slug ".$cf->getSlug().
"\t and names : ".implode($names, ', ')."</info>"); "\t and names : ".implode($names, ', ')."</info>");
} else { } else {
throw new \RuntimeException("Error in field ".$slug); throw new \RunTimeException("Error in field ".$slug);
} }
} }

View File

@@ -1,6 +1,21 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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\CustomFieldsBundle\CustomFields; namespace Chill\CustomFieldsBundle\CustomFields;
@@ -14,21 +29,36 @@ use Symfony\Bridge\Twig\TwigEngine;
use Chill\MainBundle\Form\Type\Select2ChoiceType; use Chill\MainBundle\Form\Type\Select2ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class CustomFieldLongChoice extends AbstractCustomField class CustomFieldLongChoice extends AbstractCustomField
{ {
private OptionRepository $optionRepository; /**
*
* @var OptionRepository
*/
private $optionRepository;
private TranslatableStringHelper $translatableStringHelper; /**
*
* @var TranslatableStringHelper
*/
private $translatableStringHelper;
private TwigEngine $templating; /**
* @var TwigEngine
*/
private $templating;
public const KEY = 'key'; const KEY = 'key';
public function __construct( public function __construct(OptionRepository $optionRepository,
OptionRepository $optionRepository,
TranslatableStringHelper $translatableStringHelper, TranslatableStringHelper $translatableStringHelper,
TwigEngine $twigEngine TwigEngine $twigEngine)
) { {
$this->optionRepository = $optionRepository; $this->optionRepository = $optionRepository;
$this->translatableStringHelper = $translatableStringHelper; $this->translatableStringHelper = $translatableStringHelper;
$this->templating = $twigEngine; $this->templating = $twigEngine;
@@ -46,7 +76,12 @@ class CustomFieldLongChoice extends AbstractCustomField
'choice_label' => function(Option $option) use ($translatableStringHelper) { 'choice_label' => function(Option $option) use ($translatableStringHelper) {
return $translatableStringHelper->localize($option->getText()); return $translatableStringHelper->localize($option->getText());
}, },
'choice_value' => static fn (Option $key): ?int => $key === null ? null : $key->getId(), 'choice_value' => function ($key) use ($entries) {
if ($key === NULL) {
return null;
}
return $key->getId();
},
'multiple' => false, 'multiple' => false,
'expanded' => false, 'expanded' => false,
'required' => $customField->isRequired(), 'required' => $customField->isRequired(),
@@ -54,16 +89,15 @@ class CustomFieldLongChoice extends AbstractCustomField
'group_by' => function(Option $option) use ($translatableStringHelper) { 'group_by' => function(Option $option) use ($translatableStringHelper) {
if ($option->hasParent()) { if ($option->hasParent()) {
return $translatableStringHelper->localize($option->getParent()->getText()); return $translatableStringHelper->localize($option->getParent()->getText());
} else {
return $translatableStringHelper->localize($option->getText());
} }
return $translatableStringHelper->localize($option->getText());
}, },
'label' => $translatableStringHelper->localize($customField->getName()) 'label' => $translatableStringHelper->localize($customField->getName())
)); ));
$builder->get($customField->getSlug())
->addModelTransformer(new CustomFieldDataTransformer($this, $customField));
$builder
->get($customField->getSlug())
->addModelTransformer(new CustomFieldDataTransformer($this, $customField));
} }
public function buildOptionsForm(FormBuilderInterface $builder) public function buildOptionsForm(FormBuilderInterface $builder)

View File

@@ -2,7 +2,6 @@
namespace Chill\CustomFieldsBundle\Form; namespace Chill\CustomFieldsBundle\Form;
use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
@@ -53,48 +52,50 @@ class CustomFieldsGroupType extends AbstractType
)) ))
; ;
$builder->addEventListener( $builder->addEventListener(FormEvents::POST_SET_DATA,
FormEvents::POST_SET_DATA, function(FormEvent $event) use ($customizableEntities, $builder){
function(FormEvent $event) use ($customizableEntities, $builder) { $form = $event->getForm();
$form = $event->getForm(); $group = $event->getData();
$group = $event->getData();
//stop the function if entity is not set //stop the function if entity is not set
if ($group->getEntity() === NULL) { if ($group->getEntity() === NULL) {
return; return;
} }
$optionBuilder = null; if (count($customizableEntities[$group->getEntity()]['options']) > 0) {
if (count($customizableEntities[$group->getEntity()]['options']) > 0) { $optionBuilder = $builder
$optionBuilder = $builder ->getFormFactory()
->getFormFactory() ->createBuilderForProperty(
->createBuilderForProperty(CustomFieldsGroup::class, 'options') 'Chill\CustomFieldsBundle\Entity\CustomFieldsGroup',
->create( 'options'
'options', )
null, ->create('options', null, array(
[ 'compound' => true,
'compound' => true, 'auto_initialize' => false,
'auto_initialize' => false, 'required' => false)
'required' => false );
] }
);
foreach($customizableEntities[$group->getEntity()]['options'] as $key => $option) { foreach($customizableEntities[$group->getEntity()]['options'] as $key => $option) {
$optionBuilder->add($key, $option['form_type'], $option['form_options']); $optionBuilder
->add($key, $option['form_type'], $option['form_options'])
;
}
if (isset($optionBuilder) && $optionBuilder->count() > 0) {
$form->add($optionBuilder->getForm());
} }
}
if ((null !== $optionBuilder) && $optionBuilder->count() > 0) { });
$form->add($optionBuilder->getForm());
}
});
} }
/**
* @param OptionsResolverInterface $resolver
*/
public function configureOptions(OptionsResolver $resolver) public function configureOptions(OptionsResolver $resolver)
{ {
$resolver->setDefaults([ $resolver->setDefaults(array(
'data_class' => CustomFieldsGroup::class, 'data_class' => 'Chill\CustomFieldsBundle\Entity\CustomFieldsGroup'
]); ));
} }
/** /**

View File

@@ -59,27 +59,22 @@ class CustomFieldsGroupToIdTransformer implements DataTransformerInterface
} }
if ($id instanceof CustomFieldsGroup) { if ($id instanceof CustomFieldsGroup) {
throw new TransformationFailedException( throw new TransformationFailedException(sprintf(
sprintf(
'The transformation failed: the expected argument on ' 'The transformation failed: the expected argument on '
. 'reverseTransform is an object of type int,' . 'reverseTransform is an object of type int,'
. 'Chill\CustomFieldsBundle\Entity\CustomFieldsGroup, ' . 'Chill\CustomFieldsBundle\Entity\CustomFieldsGroup, '
. 'given' . 'given', gettype($id)));
)
);
} }
$customFieldsGroup = $this->om $customFieldsGroup = $this->om
->getRepository(CustomFieldsGroup::class)->find($id) ->getRepository('ChillCustomFieldsBundle:customFieldsGroup')->find($id)
; ;
if (null === $customFieldsGroup) { if (null === $customFieldsGroup) {
throw new TransformationFailedException( throw new TransformationFailedException(sprintf(
sprintf( 'Le group avec le numéro "%s" ne peut pas être trouvé!',
'Le group avec le numéro "%s" ne peut pas être trouvé!', $id
$id ));
)
);
} }
return $customFieldsGroup; return $customFieldsGroup;

View File

@@ -1,27 +1,28 @@
<?php <?php
declare(strict_types=1);
namespace Chill\CustomFieldsBundle\Form\DataTransformer; namespace Chill\CustomFieldsBundle\Form\DataTransformer;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\DataTransformerInterface;
use Doctrine\Persistence\ObjectManager; use Doctrine\Persistence\ObjectManager;
use Doctrine\Common\Collections\ArrayCollection;
class JsonCustomFieldToArrayTransformer implements DataTransformerInterface { class JsonCustomFieldToArrayTransformer implements DataTransformerInterface {
private ObjectManager $om; /**
* @var ObjectManager
private array $customField; */
private $om;
/**
* @param ObjectManager $om
*/
public function __construct(ObjectManager $om) public function __construct(ObjectManager $om)
{ {
$this->om = $om; $this->om = $om;
$customFields = $this->om $customFields = $this->om
->getRepository(CustomField::class) ->getRepository('ChillCustomFieldsBundle:CustomField')
->findAll(); ->findAll();
// @TODO: in the array_map callback, CustomField::getLabel() does not exist. What do we do here?
$customFieldsLablels = array_map( $customFieldsLablels = array_map(
function($e) { return $e->getLabel(); }, function($e) { return $e->getLabel(); },
$customFields); $customFields);
@@ -35,12 +36,20 @@ class JsonCustomFieldToArrayTransformer implements DataTransformerInterface {
{ {
echo $customFieldsJSON; echo $customFieldsJSON;
if($customFieldsJSON === null) { if($customFieldsJSON === null) { // lors de la creation
$customFieldsArray = []; $customFieldsArray = array();
} else { } else {
$customFieldsArray = json_decode($customFieldsJSON, true, 512, JSON_THROW_ON_ERROR); $customFieldsArray = json_decode($customFieldsJSON,true);
} }
/*
echo "<br> - 4 - <br>";
var_dump($customFieldsArray);
echo "<br> - 5 - <br>";
*/
$customFieldsArrayRet = array(); $customFieldsArrayRet = array();
foreach ($customFieldsArray as $key => $value) { foreach ($customFieldsArray as $key => $value) {

View File

@@ -1,69 +0,0 @@
<?php
namespace Chill\DocGeneratorBundle\Serializer\Encoder;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
class DocGenEncoder implements \Symfony\Component\Serializer\Encoder\EncoderInterface
{
/**
* @inheritDoc
*/
public function encode($data, string $format, array $context = [])
{
if (!$this->isAssociative($data)) {
throw new UnexpectedValueException("Only associative arrays are allowed; lists are not allowed");
}
$result = [];
$this->recusiveEncoding($data, $result, '');
return $result;
}
private function recusiveEncoding(array $data, array &$result, $path)
{
if ($this->isAssociative($data)) {
foreach ($data as $key => $value) {
if (\is_array($value)) {
$this->recusiveEncoding($value, $result, $this->canonicalizeKey($path, $key));
} else {
$result[$this->canonicalizeKey($path, $key)] = $value;
}
}
} else {
foreach ($data as $elem) {
if (!$this->isAssociative($elem)) {
throw new UnexpectedValueException(sprintf("Embedded loops are not allowed. See data under %s path", $path));
}
$sub = [];
$this->recusiveEncoding($elem, $sub, '');
$result[$path][] = $sub;
}
}
}
private function canonicalizeKey(string $path, string $key): string
{
return $path === '' ? $key : $path.'_'.$key;
}
private function isAssociative(array $data)
{
$keys = \array_keys($data);
return $keys !== \array_keys($keys);
}
/**
* @inheritDoc
*/
public function supportsEncoding(string $format)
{
return $format === 'docgen';
}
}

View File

@@ -1,47 +0,0 @@
<?php
namespace Chill\DocGeneratorBundle\Serializer\Helper;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class NormalizeNullValueHelper
{
private NormalizerInterface $normalizer;
public function __construct(NormalizerInterface $normalizer)
{
$this->normalizer = $normalizer;
}
public function normalize(array $attributes, string $format = 'docgen', ?array $context = [])
{
$data = [];
foreach ($attributes as $key => $class) {
if (is_numeric($key)) {
$data[$class] = '';
} else {
switch ($class) {
case 'array':
case 'bool':
case 'double':
case 'float':
case 'int':
case 'resource':
case 'string':
case 'null':
$data[$key] = '';
break;
default:
$data[$key] = $this->normalizer->normalize(null, $format, \array_merge(
$context,
['docgen:expects' => $class]
));
break;
}
}
}
return $data;
}
}

View File

@@ -1,177 +0,0 @@
<?php
namespace Chill\DocGeneratorBundle\Serializer\Normalizer;
use Chill\DocGeneratorBundle\Serializer\Helper\NormalizeNullValueHelper;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\Serializer\Mapping\ClassMetadata;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class DocGenObjectNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private ClassMetadataFactoryInterface $classMetadataFactory;
private PropertyAccessor $propertyAccess;
public function __construct(ClassMetadataFactoryInterface $classMetadataFactory)
{
$this->classMetadataFactory = $classMetadataFactory;
$this->propertyAccess = PropertyAccess::createPropertyAccessor();
}
/**
* @inheritDoc
*/
public function normalize($object, string $format = null, array $context = [])
{
$classMetadataKey = $object ?? $context['docgen:expects'];
if (!$this->classMetadataFactory->hasMetadataFor($classMetadataKey)) {
throw new LogicException(sprintf("This object does not have metadata: %s. Add groups on this entity to allow to serialize with the format %s and groups %s", is_object($object) ? get_class($object) : $context['docgen:expects'], $format, \implode(', ', $context['groups'])));
}
$metadata = $this->classMetadataFactory->getMetadataFor($classMetadataKey);
$expectedGroups = \array_key_exists(AbstractNormalizer::GROUPS, $context) ?
\is_array($context[AbstractNormalizer::GROUPS]) ? $context[AbstractNormalizer::GROUPS] : [$context[AbstractNormalizer::GROUPS]]
: [];
$attributes = \array_filter(
$metadata->getAttributesMetadata(),
function (AttributeMetadata $a) use ($expectedGroups) {
foreach ($a->getGroups() as $g) {
if (\in_array($g, $expectedGroups, true)) {
return true;
}
}
return false;
});
if (null === $object) {
return $this->normalizeNullData($format, $context, $metadata, $attributes);
}
return $this->normalizeObject($object, $format, $context, $expectedGroups, $metadata, $attributes);
}
/**
* @param string $format
* @param array $context
* @param array $expectedGroups
* @param ClassMetadata $metadata
* @param array|AttributeMetadata[] $attributes
*/
private function normalizeNullData(string $format, array $context, ClassMetadata $metadata, array $attributes): array
{
$keys = [];
foreach ($attributes as $attribute) {
$key = $attribute->getSerializedName() ?? $attribute->getName();
$keys[$key] = $this->getExpectedType($attribute, $metadata->getReflectionClass());
}
$normalizer = new NormalizeNullValueHelper($this->normalizer);
return $normalizer->normalize($keys, $format, $context);
}
/**
* @param $object
* @param $format
* @param array $context
* @param array $expectedGroups
* @param ClassMetadata $metadata
* @param array|AttributeMetadata[] $attributes
* @return array
* @throws ExceptionInterface
*/
private function normalizeObject($object, $format, array $context, array $expectedGroups, ClassMetadata $metadata, array $attributes)
{
$data = [];
$reflection = $metadata->getReflectionClass();
foreach ($attributes as $attribute) {
/** @var AttributeMetadata $attribute */
$value = $this->propertyAccess->getValue($object, $attribute->getName());
$key = $attribute->getSerializedName() ?? $attribute->getName();
if (is_object($value)) {
$data[$key] =
$this->normalizer->normalize($value, $format, \array_merge(
$context, $attribute->getNormalizationContextForGroups($expectedGroups)
));
} elseif (null === $value) {
$data[$key] = $this->normalizeNullOutputValue($format, $context, $attribute, $reflection);
} else {
$data[$key] = (string) $value;
}
}
return $data;
}
private function getExpectedType(AttributeMetadata $attribute, \ReflectionClass $reflection): string
{
// we have to get the expected content
if ($reflection->hasProperty($attribute->getName())) {
$type = $reflection->getProperty($attribute->getName())->getType();
} elseif ($reflection->hasMethod($attribute->getName())) {
$type = $reflection->getMethod($attribute->getName())->getReturnType();
} else {
throw new \LogicException(sprintf(
"Could not determine how the content is determined for the attribute %s. Add attribute property only on property or method", $attribute->getName()
));
}
if (null === $type) {
throw new \LogicException(sprintf(
"Could not determine the type for this attribute: %s. Add a return type to the method or property declaration", $attribute->getName()
));
}
return $type->getName();
}
/**
*/
private function normalizeNullOutputValue($format, array $context, AttributeMetadata $attribute, \ReflectionClass $reflection)
{
$type = $this->getExpectedType($attribute, $reflection);
switch ($type) {
case 'array':
case 'bool':
case 'double':
case 'float':
case 'int':
case 'resource':
case 'string':
return '';
default:
return $this->normalizer->normalize(
null,
$format,
\array_merge(
$context,
['docgen:expects' => $type]
)
);
}
}
/**
* @inheritDoc
*/
public function supportsNormalization($data, string $format = null): bool
{
return $format === 'docgen' && (is_object($data) || null === $data);
}
}

View File

@@ -8,10 +8,3 @@ services:
autowire: true autowire: true
autoconfigure: true autoconfigure: true
resource: '../Repository/' resource: '../Repository/'
Chill\DocGeneratorBundle\Serializer\Normalizer\:
autowire: true
autoconfigure: true
resource: '../Serializer/Normalizer/'
tags:
- { name: 'serializer.normalizer', priority: -152 }

View File

@@ -1,32 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\Migrations\DocGenerator;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20211119173556 extends AbstractMigration
{
public function getDescription(): string
{
return 'remove comment on deprecated json_array type';
}
public function up(Schema $schema): void
{
$columns = [
'chill_docgen_template.name'
];
foreach ($columns as $col) {
$this->addSql("COMMENT ON COLUMN $col IS NULL");
}
}
public function down(Schema $schema): void
{
$this->throwIrreversibleMigrationException();
}
}

View File

@@ -1,113 +0,0 @@
<?php
namespace Chill\DocGeneratorBundle\Tests\Serializer\Encoder;
use Chill\DocGeneratorBundle\Serializer\Encoder\DocGenEncoder;
use Doctrine\ORM\EntityRepository;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
class DocGenEncoderTest extends TestCase
{
private DocGenEncoder $encoder;
protected function setUp()
{
parent::setUp();
$this->encoder = new DocGenEncoder();
}
/**
* @dataProvider generateEncodeData
*/
public function testEncode($expected, $data, string $msg)
{
$generated = $this->encoder->encode($data, 'docgen');
$this->assertEquals($expected, $generated, $msg);
}
public function testEmbeddedLoopsThrowsException()
{
$this->expectException(UnexpectedValueException::class);
$data = [
'data' => [
['item' => 'one'],
[
'embedded' => [
[
['subitem' => 'two'],
['subitem' => 'three']
]
]
],
]
];
$this->encoder->encode($data, 'docgen');
}
public function generateEncodeData()
{
yield [ ['tests' => 'ok'], ['tests' => 'ok'], "A simple test with a simple array"];
yield [
// expected:
['item_subitem' => 'value'],
// data:
['item' => ['subitem' => 'value']],
"A test with multidimensional array"
];
yield [
// expected:
[ 'data' => [['item' => 'one'], ['item' => 'two']] ],
// data:
[ 'data' => [['item' => 'one'], ['item' => 'two']] ],
"a list of items"
];
yield [
// expected:
[ 'data' => [['item_subitem' => 'alpha'], ['item' => 'two']] ],
// data:
[ 'data' => [['item' => ['subitem' => 'alpha']], ['item' => 'two'] ] ],
"a list of items with multidimensional array inside item"
];
yield [
// expected:
[
'persons' => [
[
'firstname' => 'Jonathan',
'lastname' => 'Dupont',
'dateOfBirth_long' => '16 juin 1981',
'dateOfBirth_short' => '16/06/1981',
'father_firstname' => 'Marcel',
'father_lastname' => 'Dupont',
'father_dateOfBirth_long' => '10 novembre 1953',
'father_dateOfBirth_short' => '10/11/1953'
],
]
],
// data:
[
'persons' => [
[
'firstname' => 'Jonathan',
'lastname' => 'Dupont',
'dateOfBirth' => [ 'long' => '16 juin 1981', 'short' => '16/06/1981'],
'father' => [
'firstname' => 'Marcel',
'lastname' => 'Dupont',
'dateOfBirth' => ['long' => '10 novembre 1953', 'short' => '10/11/1953']
]
],
]
],
"a longer list, with near real data inside and embedded associative arrays"
];
}
}

View File

@@ -1,80 +0,0 @@
<?php
namespace Chill\DocGeneratorBundle\tests\Serializer\Normalizer;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class DocGenObjectNormalizerTest extends KernelTestCase
{
private NormalizerInterface $normalizer;
protected function setUp()
{
parent::setUp();
self::bootKernel();
$this->normalizer = self::$container->get(NormalizerInterface::class);
}
public function testNormalizationBasic()
{
$user = new User();
$user->setUsername('User Test');
$user->setMainCenter($center = new Center());
$center->setName('test');
$normalized = $this->normalizer->normalize($user, 'docgen', [ AbstractNormalizer::GROUPS => ['docgen:read']]);
$expected = [
'label' => 'User Test',
'email' => '',
'mainCenter' => [
'name' => 'test'
]
];
$this->assertEquals($expected, $normalized, "test normalization fo an user");
}
public function testNormalizeWithNullValueEmbedded()
{
$user = new User();
$user->setUsername('User Test');
$normalized = $this->normalizer->normalize($user, 'docgen', [ AbstractNormalizer::GROUPS => ['docgen:read']]);
$expected = [
'label' => 'User Test',
'email' => '',
'mainCenter' => [
'name' => ''
]
];
$this->assertEquals($expected, $normalized, "test normalization fo an user with null center");
}
public function testNormalizeNullObjectWithObjectEmbedded()
{
$normalized = $this->normalizer->normalize(null, 'docgen', [
AbstractNormalizer::GROUPS => ['docgen:read'],
'docgen:expects' => User::class,
]);
$expected = [
'label' => '',
'email' => '',
'mainCenter' => [
'name' => ''
]
];
$this->assertEquals($expected, $normalized, "test normalization for a null user");
}
}

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\DocStoreBundle\Controller; namespace Chill\DocStoreBundle\Controller;
use Chill\DocStoreBundle\Entity\DocumentCategory; use Chill\DocStoreBundle\Entity\DocumentCategory;
@@ -11,9 +9,11 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Chill\DocStoreBundle\ChillDocStoreBundle;
/** /**
* Class DocumentCategoryController
*
* @package Chill\DocStoreBundle\Controller
* @Route("/{_locale}/admin/document/category") * @Route("/{_locale}/admin/document/category")
*/ */
class DocumentCategoryController extends AbstractController class DocumentCategoryController extends AbstractController
@@ -24,14 +24,11 @@ class DocumentCategoryController extends AbstractController
public function index(): Response public function index(): Response
{ {
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
$categories = $em->getRepository(DocumentCategory::class)->findAll(); $categories = $em->getRepository("ChillDocStoreBundle:DocumentCategory")->findAll();
return $this->render( return $this->render(
'ChillDocStoreBundle:DocumentCategory:index.html.twig', 'ChillDocStoreBundle:DocumentCategory:index.html.twig',
[ ['document_categories' => $categories]);
'document_categories' => $categories,
]
);
} }
/** /**
@@ -40,10 +37,13 @@ class DocumentCategoryController extends AbstractController
public function new(Request $request): Response public function new(Request $request): Response
{ {
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
$documentCategory = new DocumentCategory( $documentCategory = new DocumentCategory();
ChillDocStoreBundle::class, $documentCategory
$em->getRepository(DocumentCategory::class)->nextIdInsideBundle() ->setBundleId('Chill\DocStoreBundle\ChillDocStoreBundle');
); $documentCategory
->setIdInsideBundle(
$em->getRepository("ChillDocStoreBundle:DocumentCategory")
->nextIdInsideBundle());
$documentCategory $documentCategory
->setDocumentClass(PersonDocument::class); ->setDocumentClass(PersonDocument::class);
@@ -56,10 +56,11 @@ class DocumentCategoryController extends AbstractController
$em->flush(); $em->flush();
return $this->redirectToRoute('document_category_index'); return $this->redirectToRoute('document_category_index');
} else {
$documentCategory->setBundleId(
'Chill\DocStoreBundle\ChillDocStoreBundle');
} }
$documentCategory->setBundleId(ChillDocStoreBundle::class);
return $this->render('ChillDocStoreBundle:DocumentCategory:new.html.twig', [ return $this->render('ChillDocStoreBundle:DocumentCategory:new.html.twig', [
'document_category' => $documentCategory, 'document_category' => $documentCategory,
'form' => $form->createView(), 'form' => $form->createView(),

View File

@@ -34,6 +34,6 @@ class DocumentCategoryRepository extends EntityRepository
'SELECT MAX(c.idInsideBundle) + 1 FROM ChillDocStoreBundle:DocumentCategory c') 'SELECT MAX(c.idInsideBundle) + 1 FROM ChillDocStoreBundle:DocumentCategory c')
->getSingleResult(); ->getSingleResult();
return reset($array_res); return $array_res[1] ?: 0;
} }
} }

View File

@@ -1,19 +1,44 @@
<?php <?php
/*
* Copyright (C) 2018 Champs-Libres SCRLFS
*
* 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\DocStoreBundle\Security\Authorization; namespace Chill\DocStoreBundle\Security\Authorization;
use App\Security\Authorization\VoterHelperFactory;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter; use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Security\Authorization\VoterHelperFactoryInterface; use Chill\MainBundle\Security\Authorization\VoterHelperFactoryInterface;
use Chill\MainBundle\Security\Authorization\VoterHelperInterface; use Chill\MainBundle\Security\Authorization\VoterHelperInterface;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface; use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\DocStoreBundle\Entity\PersonDocument; use Chill\DocStoreBundle\Entity\PersonDocument;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\User; use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Security\Authorization\PersonVoter; use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\Role;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\Security;
/**
*
*/
class PersonDocumentVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface class PersonDocumentVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{ {
const CREATE = 'CHILL_PERSON_DOCUMENT_CREATE'; const CREATE = 'CHILL_PERSON_DOCUMENT_CREATE';

View File

@@ -1,34 +0,0 @@
<?php
declare(strict_types=1);
namespace Chill\Migrations\DocStore;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20211119173558 extends AbstractMigration
{
public function getDescription(): string
{
return 'remove comment on deprecated json_array type';
}
public function up(Schema $schema): void
{
$columns = [
'chill_doc.document_category.name',
'chill_doc.stored_object.key',
'chill_doc.stored_object.iv',
'chill_doc.stored_object.datas',
];
foreach ($columns as $col) {
$this->addSql("COMMENT ON COLUMN $col IS NULL");
}
}
public function down(Schema $schema): void
{
$this->throwIrreversibleMigrationException();
}
}

View File

@@ -23,7 +23,6 @@ use ArrayIterator;
use Chill\EventBundle\Entity\Event; use Chill\EventBundle\Entity\Event;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Chill\EventBundle\Entity\Participation; use Chill\EventBundle\Entity\Participation;
@@ -184,7 +183,7 @@ class ParticipationController extends AbstractController
$participations = $this->handleRequest($request, new Participation(), true); $participations = $this->handleRequest($request, new Participation(), true);
$ignoredParticipations = $newParticipations = []; $ignoredParticipations = $newParticipations = [];
foreach ($participations as $participation) { foreach ($participations as $i => $participation) {
// check for authorization // check for authorization
$this->denyAccessUnlessGranted(ParticipationVoter::CREATE, $this->denyAccessUnlessGranted(ParticipationVoter::CREATE,
$participation, 'The user is not allowed to create this participation'); $participation, 'The user is not allowed to create this participation');
@@ -219,9 +218,7 @@ class ParticipationController extends AbstractController
return $this->redirectToRoute('chill_event__event_show', array( return $this->redirectToRoute('chill_event__event_show', array(
'event_id' => $request->query->getInt('event_id', 0) 'event_id' => $request->query->getInt('event_id', 0)
)); ));
} } elseif (count($newParticipations) > 1) {
if (count($newParticipations) > 1) {
// if we have multiple participations, show a form with multiple participations // if we have multiple participations, show a form with multiple participations
$form = $this->createCreateFormMultiple($newParticipations); $form = $this->createCreateFormMultiple($newParticipations);
@@ -375,6 +372,9 @@ class ParticipationController extends AbstractController
* If the request is multiple, the $participation object is cloned. * If the request is multiple, the $participation object is cloned.
* Limitations: the $participation should not be persisted. * Limitations: the $participation should not be persisted.
* *
* @param Request $request
* @param Participation $participation
* @param boolean $multiple (default false)
* @return Participation|Participations[] return one single participation if $multiple == false * @return Participation|Participations[] return one single participation if $multiple == false
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the event/person is not found * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the event/person is not found
* @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException if the user does not have access to event/person * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException if the user does not have access to event/person
@@ -382,7 +382,7 @@ class ParticipationController extends AbstractController
protected function handleRequest( protected function handleRequest(
Request $request, Request $request,
Participation $participation, Participation $participation,
bool $multiple = false) $multiple = false)
{ {
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
if ($em->contains($participation)) { if ($em->contains($participation)) {
@@ -441,9 +441,11 @@ class ParticipationController extends AbstractController
} }
/** /**
* @param Participation $participation
* @param null $return_path * @param null $return_path
* @return \Symfony\Component\Form\FormInterface
*/ */
public function createCreateForm(Participation $participation, $return_path = null): FormInterface public function createCreateForm(Participation $participation, $return_path = null)
{ {
$form = $this->createForm(ParticipationType::class, $participation, array( $form = $this->createForm(ParticipationType::class, $participation, array(
@@ -462,7 +464,11 @@ class ParticipationController extends AbstractController
return $form; return $form;
} }
public function createCreateFormMultiple(array $participations): FormInterface /**
* @param array $participations
* @return \Symfony\Component\Form\FormInterface
*/
public function createCreateFormMultiple(array $participations)
{ {
$form = $this->createForm(\Symfony\Component\Form\Extension\Core\Type\FormType::class, $form = $this->createForm(\Symfony\Component\Form\Extension\Core\Type\FormType::class,
array('participations' => $participations), array( array('participations' => $participations), array(
@@ -489,16 +495,18 @@ class ParticipationController extends AbstractController
} }
/** /**
* Show an edit form for the participation with the given id. * show an edit form for the participation with the given id.
* *
* @param int $participation_id
* @return \Symfony\Component\HttpFoundation\Response
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the participation is not found * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the participation is not found
* @throws \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException if the user is not allowed to edit the participation * @throws \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException if the user is not allowed to edit the participation
*/ */
public function editAction(int $participation_id): Response public function editAction($participation_id)
{ {
/* @var $participation Participation */ /* @var $participation Participation */
$participation = $this->getDoctrine()->getManager() $participation = $this->getDoctrine()->getManager()
->getRepository(Participation::class) ->getRepository('ChillEventBundle:Participation')
->find($participation_id); ->find($participation_id);
if ($participation === NULL) { if ($participation === NULL) {
@@ -510,17 +518,22 @@ class ParticipationController extends AbstractController
$form = $this->createEditForm($participation); $form = $this->createEditForm($participation);
return $this->render('ChillEventBundle:Participation:edit.html.twig', [ return $this->render('ChillEventBundle:Participation:edit.html.twig', array(
'form' => $form->createView(), 'form' => $form->createView(),
'participation' => $participation, 'participation' => $participation
]); ));
} }
public function updateAction(int $participation_id, Request $request): Response /**
* @param $participation_id
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
*/
public function updateAction($participation_id, Request $request)
{ {
/* @var $participation Participation */ /* @var $participation Participation */
$participation = $this->getDoctrine()->getManager() $participation = $this->getDoctrine()->getManager()
->getRepository(Participation::class) ->getRepository('ChillEventBundle:Participation')
->find($participation_id); ->find($participation_id);
if ($participation === NULL) { if ($participation === NULL) {
@@ -543,40 +556,35 @@ class ParticipationController extends AbstractController
'The participation was updated' 'The participation was updated'
)); ));
return $this->redirectToRoute('chill_event__event_show', [ return $this->redirectToRoute('chill_event__event_show', array(
'event_id' => $participation->getEvent()->getId(), 'event_id' => $participation->getEvent()->getId()
]); ));
} }
return $this->render('ChillEventBundle:Participation:edit.html.twig', [ return $this->render('ChillEventBundle:Participation:edit.html.twig', array(
'form' => $form->createView(), 'form' => $form->createView(),
'participation' => $participation, 'participation' => $participation
]); ));
} }
public function createEditForm(Participation $participation): FormInterface /**
*
* @param Participation $participation
* @return \Symfony\Component\Form\FormInterface
*/
public function createEditForm(Participation $participation)
{ {
$form = $this->createForm( $form = $this->createForm(ParticipationType::class, $participation, array(
ParticipationType::class, 'event_type' => $participation->getEvent()->getType(),
$participation, 'action' => $this->generateUrl('chill_event_participation_update', array(
[ 'participation_id' => $participation->getId()
'event_type' => $participation->getEvent()->getType(), ))
'action' => $this->generateUrl( ));
'chill_event_participation_update',
[
'participation_id' => $participation->getId(),
]
),
]
);
$form->add( $form->add('submit', SubmitType::class, array(
'submit', 'label' => 'Edit'
SubmitType::class, [ ));
'label' => 'Edit',
]
);
return $form; return $form;
} }

View File

@@ -1,46 +1,50 @@
<?php <?php
declare(strict_types=1);
namespace Chill\AMLI\FamilyMembersBundle\Controller; namespace Chill\AMLI\FamilyMembersBundle\Controller;
use Chill\AMLI\FamilyMembersBundle\Repository\FamilyMemberRepository; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityManagerInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Chill\AMLI\FamilyMembersBundle\Entity\FamilyMember; use Chill\AMLI\FamilyMembersBundle\Entity\FamilyMember;
use Chill\AMLI\FamilyMembersBundle\Security\Voter\FamilyMemberVoter; use Chill\AMLI\FamilyMembersBundle\Security\Voter\FamilyMemberVoter;
use Chill\AMLI\FamilyMembersBundle\Form\FamilyMemberType; use Chill\AMLI\FamilyMembersBundle\Form\FamilyMemberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Annotation\Route;
class FamilyMemberController extends AbstractController class FamilyMemberController extends Controller
{ {
private EntityManagerInterface $em; /**
*
* @var EntityManagerInterface
*/
protected $em;
protected TranslatorInterface $translator; /**
*
* @var TranslatorInterface
*/
protected $translator;
protected LoggerInterface $chillMainLogger; /**
*
private FamilyMemberRepository $familyMemberRepository; * @var LoggerInterface
*/
protected $chillMainLogger;
public function __construct( public function __construct(
EntityManagerInterface $entityManager, EntityManagerInterface $em,
TranslatorInterface $translator, TranslatorInterface $translator,
LoggerInterface $chillMainLogger, LoggerInterface $chillMainLogger
FamilyMemberRepository $familyMemberRepository
) { ) {
$this->em = $entityManager; $this->em = $em;
$this->translator = $translator; $this->translator = $translator;
$this->chillMainLogger = $chillMainLogger; $this->chillMainLogger = $chillMainLogger;
$this->familyMemberRepository = $familyMemberRepository;
} }
/** /**
* @Route( * @Route(
* "{_locale}/family-members/family-members/by-person/{id}", * "{_locale}/family-members/family-members/by-person/{id}",
@@ -51,12 +55,14 @@ class FamilyMemberController extends AbstractController
{ {
$this->denyAccessUnlessGranted(FamilyMemberVoter::SHOW, $person); $this->denyAccessUnlessGranted(FamilyMemberVoter::SHOW, $person);
$familyMembers = $this->familyMemberRepository->findByPerson($person); $familyMembers = $this->em
->getRepository(FamilyMember::class)
->findByPerson($person);
return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:index.html.twig', [ return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:index.html.twig', array(
'person' => $person, 'person' => $person,
'familyMembers' => $familyMembers 'familyMembers' => $familyMembers
]); ));
} }
/** /**
@@ -67,7 +73,9 @@ class FamilyMemberController extends AbstractController
*/ */
public function newAction(Person $person, Request $request) public function newAction(Person $person, Request $request)
{ {
$familyMember = (new FamilyMember())->setPerson($person); $familyMember = (new FamilyMember())
->setPerson($person)
;
$this->denyAccessUnlessGranted(FamilyMemberVoter::CREATE, $familyMember); $this->denyAccessUnlessGranted(FamilyMemberVoter::CREATE, $familyMember);
@@ -76,9 +84,10 @@ class FamilyMemberController extends AbstractController
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() and $form->isValid()) {
$this->em->persist($familyMember); $em = $this->getDoctrine()->getManager();
$this->em->flush(); $em->persist($familyMember);
$em->flush();
$this->addFlash('success', $this->translator->trans('Family member created')); $this->addFlash('success', $this->translator->trans('Family member created'));
@@ -87,10 +96,10 @@ class FamilyMemberController extends AbstractController
]); ]);
} }
return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:new.html.twig', [ return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:new.html.twig', array(
'form' => $form->createView(), 'form' => $form->createView(),
'person' => $person 'person' => $person
]); ));
} }
/** /**
@@ -108,8 +117,9 @@ class FamilyMemberController extends AbstractController
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() and $form->isValid()) {
$this->em->flush(); $em = $this->getDoctrine()->getManager();
$em->flush();
$this->addFlash('success', $this->translator->trans('Family member updated')); $this->addFlash('success', $this->translator->trans('Family member updated'));
@@ -118,11 +128,11 @@ class FamilyMemberController extends AbstractController
]); ]);
} }
return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:edit.html.twig', [ return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:edit.html.twig', array(
'familyMember' => $familyMember, 'familyMember' => $familyMember,
'form' => $form->createView(), 'form' => $form->createView(),
'person' => $familyMember->getPerson() 'person' => $familyMember->getPerson()
]); ));
} }
/** /**
@@ -131,42 +141,47 @@ class FamilyMemberController extends AbstractController
* "{_locale}/family-members/family-members/{id}/delete", * "{_locale}/family-members/family-members/{id}/delete",
* name="chill_family_members_family_members_delete" * name="chill_family_members_family_members_delete"
* ) * )
*
* @param FamilyMember $familyMember
* @param Request $request
* @return \Symfony\Component\BrowserKit\Response
*/ */
public function deleteAction(FamilyMember $familyMember, Request $request): Response public function deleteAction(FamilyMember $familyMember, Request $request)
{ {
$this->denyAccessUnlessGranted(FamilyMemberVoter::DELETE, $familyMember, 'You are not ' $this->denyAccessUnlessGranted(FamilyMemberVoter::DELETE, $familyMember, 'You are not '
. 'allowed to delete this family membership'); . 'allowed to delete this family membership');
$form = $this->createDeleteForm(); $form = $this->createDeleteForm($id);
if ($request->getMethod() === Request::METHOD_DELETE) { if ($request->getMethod() === Request::METHOD_DELETE) {
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isValid()) { if ($form->isValid()) {
$this->chillMainLogger->notice("A family member has been removed", [ $this->chillMainLogger->notice("A family member has been removed", array(
'by_user' => $this->getUser()->getUsername(), 'by_user' => $this->getUser()->getUsername(),
'family_member_id' => $familyMember->getId(), 'family_member_id' => $familyMember->getId(),
'name' => $familyMember->getFirstname()." ".$familyMember->getLastname(), 'name' => $familyMember->getFirstname()." ".$familyMember->getLastname(),
'link' => $familyMember->getLink() 'link' => $familyMember->getLink()
]); ));
$this->em->remove($familyMember); $em = $this->getDoctrine()->getManager();
$this->em->flush(); $em->remove($familyMember);
$em->flush();
$this->addFlash('success', $this->translator $this->addFlash('success', $this->translator
->trans("The family member has been successfully removed.")); ->trans("The family member has been successfully removed."));
return $this->redirectToRoute('chill_family_members_family_members_index', [ return $this->redirectToRoute('chill_family_members_family_members_index', array(
'id' => $familyMember->getPerson()->getId() 'id' => $familyMember->getPerson()->getId()
]); ));
} }
} }
return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:confirm_delete.html.twig', [ return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:confirm_delete.html.twig', array(
'familyMember' => $familyMember, 'familyMember' => $familyMember,
'delete_form' => $form->createView() 'delete_form' => $form->createView()
]); ));
} }
/** /**
@@ -179,20 +194,23 @@ class FamilyMemberController extends AbstractController
{ {
$this->denyAccessUnlessGranted(FamilyMemberVoter::SHOW, $familyMember); $this->denyAccessUnlessGranted(FamilyMemberVoter::SHOW, $familyMember);
return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:view.html.twig', [ return $this->render('ChillAMLIFamilyMembersBundle:FamilyMember:view.html.twig', array(
'familyMember' => $familyMember 'familyMember' => $familyMember
]); ));
} }
/** /**
* Creates a form to delete a help request entity by id. * Creates a form to delete a help request entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/ */
private function createDeleteForm(): FormInterface private function createDeleteForm($id)
{ {
return $this return $this->createFormBuilder()
->createFormBuilder()
->setMethod(Request::METHOD_DELETE) ->setMethod(Request::METHOD_DELETE)
->add('submit', SubmitType::class, ['label' => 'Delete']) ->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm() ->getForm()
; ;
} }

View File

@@ -1,32 +1,17 @@
<?php <?php
declare(strict_types=1);
namespace Chill\AMLI\FamilyMembersBundle\Repository; namespace Chill\AMLI\FamilyMembersBundle\Repository;
use Chill\AMLI\FamilyMembersBundle\Entity\FamilyMember;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/** /**
* @method FamilyMember|null find($id, $lockMode = null, $lockVersion = null) * FamilyMemberRepository
* @method FamilyMember|null findOneBy(array $criteria, array $orderBy = null) *
* @method FamilyMember[] findAll()
* @method FamilyMember[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/ */
class FamilyMemberRepository extends ServiceEntityRepository class FamilyMemberRepository extends \Doctrine\ORM\EntityRepository
{ {
public function __construct(ManagerRegistry $registry) public function findActiveByPerson(Person $person)
{ {
parent::__construct($registry, FamilyMember::class); return $this->findBy([ 'person' => $person ]);
}
/**
* @return FamilyMember[]
*/
public function findByPerson(Person $person): array
{
return $this->findBy(['person' => $person]);
} }
} }

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\CRUD\Controller; namespace Chill\MainBundle\CRUD\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -16,39 +14,49 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
abstract class AbstractCRUDController extends AbstractController class AbstractCRUDController extends AbstractController
{ {
/** /**
* The crud configuration * The crud configuration
* *
* This configuration si defined by `chill_main['crud']` or `chill_main['apis']` * This configuration si defined by `chill_main['crud']` or `chill_main['apis']`
*
* @var array
*/ */
protected array $crudConfig = []; protected array $crudConfig = [];
/** /**
* get the instance of the entity with the given id * get the instance of the entity with the given id
* *
* @param string $id
* @return object
* @throw Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the object is not found * @throw Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the object is not found
*/ */
protected function getEntity($action, string $id, Request $request): object protected function getEntity($action, $id, Request $request): object
{ {
$e = $this $e = $this->getDoctrine()
->getDoctrine()
->getRepository($this->getEntityClass()) ->getRepository($this->getEntityClass())
->find($id); ->find($id);
if (null === $e) { if (NULL === $e) {
throw $this->createNotFoundException(sprintf("The object %s for id %s is not found", $this->getEntityClass(), $id)); throw $this->createNotFoundException(sprintf("The object %s for id %s is not found", $this->getEntityClass(), $id));
} }
return $e; return $e;
} }
/**
* Create an entity.
*
* @param string $action
* @param Request $request
* @return object
*/
protected function createEntity(string $action, Request $request): object protected function createEntity(string $action, Request $request): object
{ {
$class = $this->getEntityClass(); $type = $this->getEntityClass();
return new $class; return new $type;
} }
/** /**
@@ -56,13 +64,18 @@ abstract class AbstractCRUDController extends AbstractController
* *
* By default, count all entities. You can customize the query by * By default, count all entities. You can customize the query by
* using the method `customizeQuery`. * using the method `customizeQuery`.
*
* @param string $action
* @param Request $request
* @return int
*/ */
protected function countEntities(string $action, Request $request, $_format): int protected function countEntities(string $action, Request $request, $_format): int
{ {
return $this->buildQueryEntities($action, $request) return $this->buildQueryEntities($action, $request)
->select('COUNT(e)') ->select('COUNT(e)')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult()
;
} }
/** /**
@@ -74,6 +87,7 @@ abstract class AbstractCRUDController extends AbstractController
* The method `orderEntity` is called internally to order entities. * The method `orderEntity` is called internally to order entities.
* *
* It returns, by default, a query builder. * It returns, by default, a query builder.
*
*/ */
protected function queryEntities(string $action, Request $request, string $_format, PaginatorInterface $paginator) protected function queryEntities(string $action, Request $request, string $_format, PaginatorInterface $paginator)
{ {
@@ -87,6 +101,7 @@ abstract class AbstractCRUDController extends AbstractController
/** /**
* Add ordering fields in the query build by self::queryEntities * Add ordering fields in the query build by self::queryEntities
*
*/ */
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format) protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
{ {
@@ -103,6 +118,8 @@ abstract class AbstractCRUDController extends AbstractController
* *
* The alias for the entity is "e". * The alias for the entity is "e".
* *
* @param string $action
* @param Request $request
* @return QueryBuilder * @return QueryBuilder
*/ */
protected function buildQueryEntities(string $action, Request $request) protected function buildQueryEntities(string $action, Request $request)
@@ -110,7 +127,8 @@ abstract class AbstractCRUDController extends AbstractController
$qb = $this->getDoctrine()->getManager() $qb = $this->getDoctrine()->getManager()
->createQueryBuilder() ->createQueryBuilder()
->select('e') ->select('e')
->from($this->getEntityClass(), 'e'); ->from($this->getEntityClass(), 'e')
;
$this->customizeQuery($action, $request, $qb); $this->customizeQuery($action, $request, $qb);
@@ -120,7 +138,7 @@ abstract class AbstractCRUDController extends AbstractController
protected function customizeQuery(string $action, Request $request, $query): void {} protected function customizeQuery(string $action, Request $request, $query): void {}
/** /**
* Get the result of the query. * Get the result of the query
*/ */
protected function getQueryResult(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query) protected function getQueryResult(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query)
{ {
@@ -133,7 +151,7 @@ abstract class AbstractCRUDController extends AbstractController
} }
/** /**
* Method used by indexAction. * method used by indexAction
*/ */
protected function onPreIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator): ?Response protected function onPreIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator): ?Response
{ {
@@ -141,7 +159,7 @@ abstract class AbstractCRUDController extends AbstractController
} }
/** /**
* Method used by indexAction. * method used by indexAction
*/ */
protected function onPostIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query): ?Response protected function onPostIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query): ?Response
{ {
@@ -149,17 +167,18 @@ abstract class AbstractCRUDController extends AbstractController
} }
/** /**
* Method used by indexAction. * method used by indexAction
*/ */
protected function onPostIndexFetchQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $entities): ?Response protected function onPostIndexFetchQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $entities): ?Response
{ {
return null; return null;
} }
/** /**
* Get the FQDN of the class. * Get the complete FQDN of the class
* *
* @return class-string The FQDN of the class * @return string the complete fqdn of the class
*/ */
protected function getEntityClass(): string protected function getEntityClass(): string
{ {
@@ -167,7 +186,7 @@ abstract class AbstractCRUDController extends AbstractController
} }
/** /**
* Called on post fetch entity. * called on post fetch entity
*/ */
protected function onPostFetchEntity(string $action, Request $request, $entity, $_format): ?Response protected function onPostFetchEntity(string $action, Request $request, $entity, $_format): ?Response
{ {
@@ -175,7 +194,7 @@ abstract class AbstractCRUDController extends AbstractController
} }
/** /**
* Called on post check ACL. * Called on post check ACL
*/ */
protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response
{ {
@@ -195,12 +214,12 @@ abstract class AbstractCRUDController extends AbstractController
*/ */
protected function checkACL(string $action, Request $request, string $_format, $entity = null) protected function checkACL(string $action, Request $request, string $_format, $entity = null)
{ {
// @TODO: Implements abstract getRoleFor method or do it in the interface.
$this->denyAccessUnlessGranted($this->getRoleFor($action, $request, $entity, $_format), $entity); $this->denyAccessUnlessGranted($this->getRoleFor($action, $request, $entity, $_format), $entity);
} }
/** /**
* @return string The crud name. *
* @return string the crud name
*/ */
protected function getCrudName(): string protected function getCrudName(): string
{ {
@@ -222,6 +241,9 @@ abstract class AbstractCRUDController extends AbstractController
$this->crudConfig = $config; $this->crudConfig = $config;
} }
/**
* @return PaginatorFactory
*/
protected function getPaginatorFactory(): PaginatorFactory protected function getPaginatorFactory(): PaginatorFactory
{ {
return $this->container->get('chill_main.paginator_factory'); return $this->container->get('chill_main.paginator_factory');
@@ -232,6 +254,9 @@ abstract class AbstractCRUDController extends AbstractController
return $this->get('validator'); return $this->get('validator');
} }
/**
* @return array
*/
public static function getSubscribedServices(): array public static function getSubscribedServices(): array
{ {
return \array_merge( return \array_merge(

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\CRUD\Controller; namespace Chill\MainBundle\CRUD\Controller;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -36,7 +34,7 @@ class ApiController extends AbstractCRUDController
*/ */
protected function entityGet(string $action, Request $request, $id, $_format = 'html'): Response protected function entityGet(string $action, Request $request, $id, $_format = 'html'): Response
{ {
$entity = $this->getEntity($action, $id, $request); $entity = $this->getEntity($action, $id, $request, $_format);
$postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format); $postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format);
@@ -88,7 +86,7 @@ class ApiController extends AbstractCRUDController
case Request::METHOD_PATCH: case Request::METHOD_PATCH:
return $this->entityPut('_entity', $request, $id, $_format); return $this->entityPut('_entity', $request, $id, $_format);
case Request::METHOD_POST: case Request::METHOD_POST:
return $this->entityPostAction('_entity', $request, $id); return $this->entityPostAction('_entity', $request, $id, $_format);
case Request::METHOD_DELETE: case Request::METHOD_DELETE:
return $this->entityDelete('_entity', $request, $id, $_format); return $this->entityDelete('_entity', $request, $id, $_format);
default: default:
@@ -160,7 +158,7 @@ class ApiController extends AbstractCRUDController
} }
public function entityPut($action, Request $request, $id, string $_format): Response public function entityPut($action, Request $request, $id, string $_format): Response
{ {
$entity = $this->getEntity($action, $id, $request); $entity = $this->getEntity($action, $id, $request, $_format);
$postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format); $postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format);
if ($postFetch instanceof Response) { if ($postFetch instanceof Response) {
@@ -223,7 +221,7 @@ class ApiController extends AbstractCRUDController
} }
public function entityDelete($action, Request $request, $id, string $_format): Response public function entityDelete($action, Request $request, $id, string $_format): Response
{ {
$entity = $this->getEntity($action, $id, $request); $entity = $this->getEntity($action, $id, $request, $_format);
if (NULL === $entity) { if (NULL === $entity) {
throw $this->createNotFoundException(sprintf("The %s with id %s " throw $this->createNotFoundException(sprintf("The %s with id %s "
@@ -347,6 +345,7 @@ class ApiController extends AbstractCRUDController
* *
* @param string $action * @param string $action
* @param Request $request * @param Request $request
* @return type
*/ */
protected function indexApiAction($action, Request $request, $_format) protected function indexApiAction($action, Request $request, $_format)
{ {
@@ -357,7 +356,9 @@ class ApiController extends AbstractCRUDController
return $response; return $response;
} }
$entity = ''; if (!isset($entity)) {
$entity = '';
}
$response = $this->onPostCheckACL($action, $request, $_format, $entity); $response = $this->onPostCheckACL($action, $request, $_format, $entity);
if ($response instanceof Response) { if ($response instanceof Response) {
@@ -367,13 +368,8 @@ class ApiController extends AbstractCRUDController
$totalItems = $this->countEntities($action, $request, $_format); $totalItems = $this->countEntities($action, $request, $_format);
$paginator = $this->getPaginatorFactory()->create($totalItems); $paginator = $this->getPaginatorFactory()->create($totalItems);
$response = $this->onPreIndexBuildQuery( $response = $this->onPreIndexBuildQuery($action, $request, $_format, $totalItems,
$action, $paginator);
$request,
$_format,
$totalItems,
$paginator
);
if ($response instanceof Response) { if ($response instanceof Response) {
return $response; return $response;

View File

@@ -1,4 +1,22 @@
<?php <?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2019, Champs Libres Cooperative SCRLFS, <http://www.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\Controller; namespace Chill\MainBundle\CRUD\Controller;
@@ -19,40 +37,60 @@ use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper; use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\SerializerInterface;
/**
* Class CRUDController
*
* @package Chill\MainBundle\CRUD\Controller
*/
class CRUDController extends AbstractController class CRUDController extends AbstractController
{ {
/** /**
* The crud configuration * The crud configuration
* *
* This configuration si defined by `chill_main['crud']`. * This configuration si defined by `chill_main['crud']`.
*
* @var array
*/ */
protected array $crudConfig; protected $crudConfig;
public function setCrudConfig(array $config): void /**
* @param array $config
*/
public function setCrudConfig(array $config)
{ {
$this->crudConfig = $config; $this->crudConfig = $config;
} }
public function CRUD(?string $parameter): Response /**
* @param $parameter
* @return Response
*/
public function CRUD($parameter)
{ {
return new Response($parameter); return new Response($parameter);
} }
/** /**
* @param Request $request
* @param $id * @param $id
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
*/ */
public function delete(Request $request, $id): Response public function delete(Request $request, $id)
{ {
return $this->deleteAction('delete', $request, $id); return $this->deleteAction('delete', $request, $id);
} }
/** /**
* @param string $action
* @param Request $request
* @param $id * @param $id
* @param null $formClass * @param null $formClass
* @return null|\Symfony\Component\HttpFoundation\RedirectResponse|Response|void
*/ */
protected function deleteAction(string $action, Request $request, $id, $formClass = null): Response protected function deleteAction(string $action, Request $request, $id, $formClass = null)
{ {
$this->onPreDelete($action, $request); $this->onPreDelete($action, $request, $id);
$entity = $this->getEntity($action, $id, $request); $entity = $this->getEntity($action, $id, $request);
@@ -63,13 +101,8 @@ class CRUDController extends AbstractController
} }
if (NULL === $entity) { if (NULL === $entity) {
throw $this->createNotFoundException( throw $this->createNotFoundException(sprintf("The %s with id %s "
sprintf( . "is not found"), $this->getCrudName(), $id);
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
} }
$response = $this->checkACL($action, $entity); $response = $this->checkACL($action, $entity);
@@ -108,9 +141,7 @@ class CRUDController extends AbstractController
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_view', ['id' => $entity->getId()]); return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_view', ['id' => $entity->getId()]);
} } elseif ($form->isSubmitted()) {
if ($form->isSubmitted()) {
$this->addFlash('error', $this->generateFormErrorMessage($action, $form)); $this->addFlash('error', $this->generateFormErrorMessage($action, $form));
} }
@@ -202,6 +233,7 @@ class CRUDController extends AbstractController
* *
* @param string $action * @param string $action
* @param Request $request * @param Request $request
* @return type
*/ */
protected function indexEntityAction($action, Request $request) protected function indexEntityAction($action, Request $request)
{ {
@@ -212,7 +244,9 @@ class CRUDController extends AbstractController
return $response; return $response;
} }
$entity = ''; if (!isset($entity)) {
$entity = '';
}
$response = $this->onPostCheckACL($action, $request, $entity); $response = $this->onPostCheckACL($action, $request, $entity);
if ($response instanceof Response) { if ($response instanceof Response) {
@@ -308,12 +342,11 @@ class CRUDController extends AbstractController
*/ */
protected function buildQueryEntities(string $action, Request $request) protected function buildQueryEntities(string $action, Request $request)
{ {
$query = $this $query = $this->getDoctrine()->getManager()
->getDoctrine()
->getManager()
->createQueryBuilder() ->createQueryBuilder()
->select('e') ->select('e')
->from($this->getEntityClass(), 'e'); ->from($this->getEntityClass(), 'e')
;
$this->customizeQuery($action, $request, $query); $this->customizeQuery($action, $request, $query);
@@ -338,7 +371,7 @@ class CRUDController extends AbstractController
*/ */
protected function queryEntities(string $action, Request $request, PaginatorInterface $paginator, ?FilterOrderHelper $filterOrder = null) protected function queryEntities(string $action, Request $request, PaginatorInterface $paginator, ?FilterOrderHelper $filterOrder = null)
{ {
$query = $this->buildQueryEntities($action, $request) $query = $this->buildQueryEntities($action, $request, $filterOrder)
->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber()) ->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber())
->setMaxResults($paginator->getItemsPerPage()); ->setMaxResults($paginator->getItemsPerPage());
@@ -387,7 +420,7 @@ class CRUDController extends AbstractController
*/ */
protected function countEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null): int protected function countEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null): int
{ {
return $this->buildQueryEntities($action, $request) return $this->buildQueryEntities($action, $request, $filterOrder)
->select('COUNT(e)') ->select('COUNT(e)')
->getQuery() ->getQuery()
->getSingleScalarResult() ->getSingleScalarResult()
@@ -472,13 +505,8 @@ class CRUDController extends AbstractController
} }
if (NULL === $entity) { if (NULL === $entity) {
throw $this->createNotFoundException( throw $this->createNotFoundException(sprintf("The %s with id %s "
sprintf( . "is not found", $this->getCrudName(), $id));
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
} }
$response = $this->checkACL($action, $entity); $response = $this->checkACL($action, $entity);
@@ -570,13 +598,8 @@ class CRUDController extends AbstractController
$entity = $this->getEntity($action, $id, $request); $entity = $this->getEntity($action, $id, $request);
if (NULL === $entity) { if (NULL === $entity) {
throw $this->createNotFoundException( throw $this->createNotFoundException(sprintf("The %s with id %s "
sprintf( . "is not found", $this->getCrudName(), $id));
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
} }
$response = $this->checkACL($action, $entity); $response = $this->checkACL($action, $entity);

View File

@@ -1,6 +1,22 @@
<?php <?php
/*
declare(strict_types=1); * Chill is a software for social workers
*
* Copyright (C) 2019, Champs Libres Cooperative SCRLFS, <http://www.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\Routing; namespace Chill\MainBundle\CRUD\Routing;
@@ -11,13 +27,22 @@ use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\CRUD\Controller\ApiController; use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\CRUD\Controller\CRUDController; use Chill\MainBundle\CRUD\Controller\CRUDController;
/**
* Class CRUDRoutesLoader
* Load the route for CRUD
*
* @package Chill\MainBundle\CRUD\Routing
*/
class CRUDRoutesLoader extends Loader class CRUDRoutesLoader extends Loader
{ {
protected array $crudConfig = []; protected array $crudConfig = [];
protected array $apiCrudConfig = []; protected array $apiCrudConfig = [];
private bool $isLoaded = false; /**
* @var bool
*/
private $isLoaded = false;
private const ALL_SINGLE_METHODS = [ private const ALL_SINGLE_METHODS = [
Request::METHOD_GET, Request::METHOD_GET,
@@ -28,12 +53,16 @@ class CRUDRoutesLoader extends Loader
private const ALL_INDEX_METHODS = [ Request::METHOD_GET, Request::METHOD_HEAD ]; private const ALL_INDEX_METHODS = [ Request::METHOD_GET, Request::METHOD_HEAD ];
public function __construct(array $crudConfig, array $apiCrudConfig) /**
* CRUDRoutesLoader constructor.
*
* @param $crudConfig the config from cruds
* @param $apicrudConfig the config from api_crud
*/
public function __construct(array $crudConfig, array $apiConfig)
{ {
$this->crudConfig = $crudConfig; $this->crudConfig = $crudConfig;
$this->apiCrudConfig = $apiCrudConfig; $this->apiConfig = $apiConfig;
parent::__construct();
} }
/** /**
@@ -60,7 +89,7 @@ class CRUDRoutesLoader extends Loader
foreach ($this->crudConfig as $crudConfig) { foreach ($this->crudConfig as $crudConfig) {
$collection->addCollection($this->loadCrudConfig($crudConfig)); $collection->addCollection($this->loadCrudConfig($crudConfig));
} }
foreach ($this->apiCrudConfig as $crudConfig) { foreach ($this->apiConfig as $crudConfig) {
$collection->addCollection($this->loadApi($crudConfig)); $collection->addCollection($this->loadApi($crudConfig));
} }

View File

@@ -3,7 +3,6 @@
namespace Chill\MainBundle; namespace Chill\MainBundle;
use Chill\MainBundle\Routing\LocalMenuBuilderInterface; use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Chill\MainBundle\Search\SearchApiInterface;
use Chill\MainBundle\Search\SearchInterface; use Chill\MainBundle\Search\SearchInterface;
use Chill\MainBundle\Security\Authorization\ChillVoterInterface; use Chill\MainBundle\Security\Authorization\ChillVoterInterface;
use Chill\MainBundle\Security\ProvideRoleInterface; use Chill\MainBundle\Security\ProvideRoleInterface;
@@ -42,8 +41,6 @@ class ChillMainBundle extends Bundle
->addTag('chill_main.scope_resolver'); ->addTag('chill_main.scope_resolver');
$container->registerForAutoconfiguration(ChillEntityRenderInterface::class) $container->registerForAutoconfiguration(ChillEntityRenderInterface::class)
->addTag('chill.render_entity'); ->addTag('chill.render_entity');
$container->registerForAutoconfiguration(SearchApiInterface::class)
->addTag('chill.search_api_provider');
$container->addCompilerPass(new SearchableServicesCompilerPass()); $container->addCompilerPass(new SearchableServicesCompilerPass());
$container->addCompilerPass(new ConfigConsistencyCompilerPass()); $container->addCompilerPass(new ConfigConsistencyCompilerPass());

View File

@@ -1,10 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Command; namespace Chill\MainBundle\Command;
use Chill\MainBundle\Repository\UserRepository;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
@@ -26,51 +23,101 @@ use League\Csv\Writer;
class ChillImportUsersCommand extends Command class ChillImportUsersCommand extends Command
{ {
protected EntityManagerInterface $em;
protected ValidatorInterface $validator; /**
*
* @var EntityManagerInterface
*/
protected $em;
protected LoggerInterface $logger; /**
*
* @var ValidatorInterface
*/
protected $validator;
protected UserPasswordEncoderInterface $passwordEncoder; /**
*
* @var LoggerInterface
*/
protected $logger;
protected UserRepository $userRepository; /**
*
* @var UserPasswordEncoderInterface
*/
protected $passwordEncoder;
protected bool $doChanges = true; /**
*
* @var \Chill\MainBundle\Repository\UserRepository
*/
protected $userRepository;
protected OutputInterface $tempOutput; /**
*
* @var bool
*/
protected $doChanges = true;
protected InputInterface $tempInput; /**
*
* @var OutputInterface
*/
protected $tempOutput;
/**
*
* @var InputInterface
*/
protected $tempInput;
/** /**
* Centers and aliases. * Centers and aliases.
* *
* key are aliases, values are an array of centers * key are aliases, values are an array of centers
*
* @var array
*/ */
protected array $centers; protected $centers = [];
protected array $permissionGroups; /**
*
* @var array
*/
protected $permissionGroups = [];
protected array $groupCenters; /**
*
* @var array
*/
protected $groupCenters = [];
protected Writer $output; /**
*
* @var Writer
*/
protected $output = null;
public function __construct( public function __construct(
EntityManagerInterface $em, EntityManagerInterface $em,
LoggerInterface $logger, LoggerInterface $logger,
UserPasswordEncoderInterface $passwordEncoder, UserPasswordEncoderInterface $passwordEncoder,
ValidatorInterface $validator, ValidatorInterface $validator
UserRepository $userRepository
) { ) {
$this->em = $em; $this->em = $em;
$this->passwordEncoder = $passwordEncoder; $this->passwordEncoder = $passwordEncoder;
$this->validator = $validator; $this->validator = $validator;
$this->logger = $logger; $this->logger = $logger;
$this->userRepository = $userRepository;
$this->userRepository = $em->getRepository(User::class);
parent::__construct('chill:main:import-users'); parent::__construct('chill:main:import-users');
} }
protected function configure() protected function configure()
{ {
$this $this
@@ -79,7 +126,8 @@ class ChillImportUsersCommand extends Command
->addArgument('csvfile', InputArgument::REQUIRED, 'Path to the csv file. Columns are: `username`, `email`, `center` (can contain alias), `permission group`') ->addArgument('csvfile', InputArgument::REQUIRED, 'Path to the csv file. Columns are: `username`, `email`, `center` (can contain alias), `permission group`')
->addOption('grouping-centers', null, InputOption::VALUE_OPTIONAL, 'Path to a csv file to aggregate multiple centers into a single alias') ->addOption('grouping-centers', null, InputOption::VALUE_OPTIONAL, 'Path to a csv file to aggregate multiple centers into a single alias')
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Do not commit the changes') ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Do not commit the changes')
->addOption('csv-dump', null, InputOption::VALUE_REQUIRED, 'A path to dump a summary of the created file'); ->addOption('csv-dump', null, InputOption::VALUE_REQUIRED, 'A path to dump a summary of the created file')
;
} }
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
@@ -261,14 +309,21 @@ class ChillImportUsersCommand extends Command
} }
return $this->permissionGroups[$alias]; return $this->permissionGroups[$alias];
} else {
$this->logger->error("Error while responding to a a question");
$this->tempOutput("Ok, I accept, but I do not know what to do. Please try again.");
throw new \RuntimeException("Error while responding to a question");
} }
$this->logger->error('Error while responding to a a question');
$this->tempOutput->writeln('Ok, I accept, but I do not know what to do. Please try again.');
throw new \RuntimeException('Error while responding to a question');
} }
/**
*
* @param Center $center
* @param \Chill\MainBundle\Command\PermissionGroup $pg
* @return GroupCenter
*/
protected function createOrGetGroupCenter(Center $center, PermissionsGroup $pg): GroupCenter protected function createOrGetGroupCenter(Center $center, PermissionsGroup $pg): GroupCenter
{ {
if (\array_key_exists($center->getId(), $this->groupCenters)) { if (\array_key_exists($center->getId(), $this->groupCenters)) {

View File

@@ -1,13 +1,27 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2016 Champs-Libres <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\Command; namespace Chill\MainBundle\Command;
use Chill\MainBundle\Doctrine\Model\Point; use Chill\MainBundle\Doctrine\Model\Point;
use Chill\MainBundle\Entity\Country; use Chill\MainBundle\Entity\Country;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
@@ -17,13 +31,32 @@ use Symfony\Component\Filesystem\Filesystem;
use Chill\MainBundle\Entity\PostalCode; use Chill\MainBundle\Entity\PostalCode;
use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class LoadPostalCodesCommand
*
* @package Chill\MainBundle\Command
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class LoadPostalCodesCommand extends Command class LoadPostalCodesCommand extends Command
{ {
private EntityManagerInterface $entityManager;
private ValidatorInterface $validator; /**
* @var EntityManager
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager, ValidatorInterface $validator) /**
* @var ValidatorInterface
*/
private $validator;
/**
* LoadPostalCodesCommand constructor.
*
* @param EntityManager $entityManager
* @param ValidatorInterface $validator
*/
public function __construct(EntityManager $entityManager, ValidatorInterface $validator)
{ {
$this->entityManager = $entityManager; $this->entityManager = $entityManager;
$this->validator = $validator; $this->validator = $validator;
@@ -69,7 +102,12 @@ class LoadPostalCodesCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
$csv = $this->getCSVResource($input); try {
$csv = $this->getCSVResource($input);
} catch (\RuntimeException $e) {
$output->writeln('<error>Error during opening the csv file : '.
$e->getMessage().'</error>');
}
if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) { if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) {
$output->writeln('The content of the file is ...'); $output->writeln('The content of the file is ...');

View File

@@ -1,12 +1,20 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Controller; namespace Chill\MainBundle\Controller;
use Chill\MainBundle\CRUD\Controller\CRUDController; use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Pagination\PaginatorFactory;
/**
*
*
*/
class AdminCountryCRUDController extends CRUDController class AdminCountryCRUDController extends CRUDController
{ {
function __construct(PaginatorFactory $paginator)
{
$this->paginatorFactory = $paginator;
}
} }

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Controller; namespace Chill\MainBundle\Controller;
use Chill\MainBundle\CRUD\Controller\AbstractCRUDController; use Chill\MainBundle\CRUD\Controller\AbstractCRUDController;
@@ -9,7 +7,6 @@ use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorInterface; use Chill\MainBundle\Pagination\PaginatorInterface;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -19,23 +16,40 @@ use Chill\MainBundle\Form\UserType;
use Chill\MainBundle\Entity\GroupCenter; use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Form\Type\ComposedGroupCenterType; use Chill\MainBundle\Form\Type\ComposedGroupCenterType;
use Chill\MainBundle\Form\UserPasswordType; use Chill\MainBundle\Form\UserPasswordType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter;
/**
* Class UserController
*
* @package Chill\MainBundle\Controller
*/
class UserController extends CRUDController class UserController extends CRUDController
{ {
const FORM_GROUP_CENTER_COMPOSED = 'composed_groupcenter'; const FORM_GROUP_CENTER_COMPOSED = 'composed_groupcenter';
private LoggerInterface $logger; /**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
private ValidatorInterface $validator; /**
* @var ValidatorInterface
*/
private $validator;
private UserPasswordEncoderInterface $passwordEncoder; private UserPasswordEncoderInterface $passwordEncoder;
/**
* UserController constructor.
*
* @param LoggerInterface $logger
* @param ValidatorInterface $validator
*/
public function __construct( public function __construct(
LoggerInterface $chillLogger, LoggerInterface $chillLogger,
ValidatorInterface $validator, ValidatorInterface $validator,
@@ -107,7 +121,7 @@ class UserController extends CRUDController
*/ */
public function editPasswordAction(User $user, Request $request) public function editPasswordAction(User $user, Request $request)
{ {
$editForm = $this->createEditPasswordForm($user); $editForm = $this->createEditPasswordForm($user, $request);
$editForm->handleRequest($request); $editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) { if ($editForm->isSubmitted() && $editForm->isValid()) {
@@ -136,17 +150,20 @@ class UserController extends CRUDController
]); ]);
} }
private function createEditPasswordForm(User $user): FormInterface /**
*
*
* @param User $user
* @return \Symfony\Component\Form\Form
*/
private function createEditPasswordForm(User $user)
{ {
return $this->createForm( return $this->createForm(UserPasswordType::class, null, array(
UserPasswordType::class, 'user' => $user
null, ))
[
'user' => $user
]
)
->add('submit', SubmitType::class, array('label' => 'Change password')) ->add('submit', SubmitType::class, array('label' => 'Change password'))
->remove('actual_password'); ->remove('actual_password')
;
} }
/** /**
@@ -191,7 +208,7 @@ class UserController extends CRUDController
* @Route("/{_locale}/admin/main/user/{uid}/add_link_groupcenter", * @Route("/{_locale}/admin/main/user/{uid}/add_link_groupcenter",
* name="admin_user_add_groupcenter") * name="admin_user_add_groupcenter")
*/ */
public function addLinkGroupCenterAction(Request $request, $uid): Response public function addLinkGroupCenterAction(Request $request, $uid): RedirectResponse
{ {
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
@@ -221,22 +238,23 @@ class UserController extends CRUDController
return $this->redirect($this->generateUrl('chill_crud_admin_user_edit', return $this->redirect($this->generateUrl('chill_crud_admin_user_edit',
\array_merge(['id' => $uid], $returnPathParams))); \array_merge(['id' => $uid], $returnPathParams)));
} } else {
foreach($this->validator->validate($user) as $error)
foreach($this->validator->validate($user) as $error) {
$this->addFlash('error', $error->getMessage()); $this->addFlash('error', $error->getMessage());
} }
} }
return $this->render('@ChillMain/User/edit.html.twig', [ return $this->render('@ChillMain/User/edit.html.twig', array(
'entity' => $user, 'entity' => $user,
'edit_form' => $this->createEditForm($user)->createView(), 'edit_form' => $this->createEditForm($user)->createView(),
'add_groupcenter_form' => $this->createAddLinkGroupCenterForm($user, $request)->createView(), 'add_groupcenter_form' => $this->createAddLinkGroupCenterForm($user)->createView(),
'delete_groupcenter_form' => array_map( 'delete_groupcenter_form' => array_map(
static fn(Form $form) => $form->createView(), function(\Symfony\Component\Form\Form $form) {
iterator_to_array($this->getDeleteLinkGroupCenterByUser($user, $request), true) return $form->createView();
)
]); },
iterator_to_array($this->getDeleteLinkGroupCenterByUser($user), true))
));
} }
private function getPersistedGroupCenter(GroupCenter $groupCenter) private function getPersistedGroupCenter(GroupCenter $groupCenter)
@@ -261,8 +279,10 @@ class UserController extends CRUDController
* Creates a form to delete a link to a GroupCenter * Creates a form to delete a link to a GroupCenter
* *
* @param mixed $permissionsGroup The entity id * @param mixed $permissionsGroup The entity id
*
* @return \Symfony\Component\Form\Form The form
*/ */
private function createDeleteLinkGroupCenterForm(User $user, GroupCenter $groupCenter, $request): FormInterface private function createDeleteLinkGroupCenterForm(User $user, GroupCenter $groupCenter, $request)
{ {
$returnPathParams = $request->query->has('returnPath') ? ['returnPath' => $request->query->get('returnPath')] : []; $returnPathParams = $request->query->has('returnPath') ? ['returnPath' => $request->query->get('returnPath')] : [];
@@ -271,29 +291,39 @@ class UserController extends CRUDController
array_merge($returnPathParams, ['uid' => $user->getId(), 'gcid' => $groupCenter->getId()]))) array_merge($returnPathParams, ['uid' => $user->getId(), 'gcid' => $groupCenter->getId()])))
->setMethod('DELETE') ->setMethod('DELETE')
->add('submit', SubmitType::class, array('label' => 'Delete')) ->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm(); ->getForm()
;
} }
/** /**
* Create a form to add a link to a groupcenter. * create a form to add a link to a groupcenter
*
* @param User $user
* @return \Symfony\Component\Form\Form
*/ */
private function createAddLinkGroupCenterForm(User $user, Request $request): FormInterface private function createAddLinkGroupCenterForm(User $user, Request $request)
{ {
$returnPathParams = $request->query->has('returnPath') ? ['returnPath' => $request->query->get('returnPath')] : []; $returnPathParams = $request->query->has('returnPath') ? ['returnPath' => $request->query->get('returnPath')] : [];
return $this->createFormBuilder() return $this->createFormBuilder()
->setAction($this->generateUrl('admin_user_add_groupcenter', ->setAction($this->generateUrl('admin_user_add_groupcenter',
array_merge($returnPathParams, ['uid' => $user->getId()]))) array_merge($returnPathParams, ['uid' => $user->getId()])))
->setMethod('POST') ->setMethod('POST')
->add(self::FORM_GROUP_CENTER_COMPOSED, ComposedGroupCenterType::class) ->add(self::FORM_GROUP_CENTER_COMPOSED, ComposedGroupCenterType::class)
->add('submit', SubmitType::class, array('label' => 'Add a new groupCenter')) ->add('submit', SubmitType::class, array('label' => 'Add a new groupCenter'))
->getForm(); ->getForm()
;
} }
/**
*
* @param User $user
*/
private function getDeleteLinkGroupCenterByUser(User $user, Request $request) private function getDeleteLinkGroupCenterByUser(User $user, Request $request)
{ {
foreach ($user->getGroupCenters() as $groupCenter) { foreach ($user->getGroupCenters() as $groupCenter) {
yield $groupCenter->getId() => $this->createDeleteLinkGroupCenterForm($user, $groupCenter, $request); yield $groupCenter->getId() => $this
->createDeleteLinkGroupCenterForm($user, $groupCenter, $request);
} }
} }
} }

View File

@@ -1,19 +1,32 @@
<?php <?php
/*
declare(strict_types=1); * Chill is a software for social workers
* Copyright (C) 2018 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\Doctrine\DQL; namespace Chill\MainBundle\Doctrine\DQL;
use Doctrine\ORM\Query\AST\Functions\FunctionNode; use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\PathExpression;
use Doctrine\ORM\Query\Lexer; use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
/** /**
* DQL function for OVERLAPS function in postgresql * DQL function for OVERLAPS function in postgresql
* *
* If a value is null in period start, it will be replaced by -infinity. * If a value is null in period start, it will be replaced by -infinity.
* If a value is null in period end, it will be replaced by infinity * If a value is null in period end, it will be replaced by infinity
*
*/ */
class OverlapsI extends FunctionNode class OverlapsI extends FunctionNode
{ {
@@ -27,17 +40,19 @@ class OverlapsI extends FunctionNode
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{ {
return sprintf( return '('
'(%s, %s) OVERLAPS (%s, %s)', .$this->makeCase($sqlWalker, $this->firstPeriodStart, 'start').', '
$this->makeCase($sqlWalker, $this->firstPeriodStart, 'start'), .$this->makeCase($sqlWalker, $this->firstPeriodEnd, 'end').
$this->makeCase($sqlWalker, $this->firstPeriodEnd, 'end'), ') OVERLAPS ('
$this->makeCase($sqlWalker, $this->secondPeriodStart, 'start'), .$this->makeCase($sqlWalker, $this->secondPeriodStart, 'start').', '
$this->makeCase($sqlWalker, $this->secondPeriodEnd, 'end') .$this->makeCase($sqlWalker, $this->secondPeriodEnd, 'end').')'
); ;
} }
protected function makeCase($sqlWalker, $part, string $position): string protected function makeCase($sqlWalker, $part, $position)
{ {
//return $part->dispatch($sqlWalker);
switch ($position) { switch ($position) {
case 'start' : case 'start' :
$p = '-infinity'; $p = '-infinity';
@@ -45,28 +60,28 @@ class OverlapsI extends FunctionNode
case 'end': case 'end':
$p = 'infinity'; $p = 'infinity';
break; break;
default:
throw new \Exception('Unexpected position value.');
} }
if ($part instanceof PathExpression) { if ($part instanceof \Doctrine\ORM\Query\AST\PathExpression) {
return sprintf( return 'CASE WHEN '
"CASE WHEN %s IS NOT NULL THEN %s ELSE '%s'::date END", .' '.$part->dispatch($sqlWalker).' IS NOT NULL '
$part->dispatch($sqlWalker), . 'THEN '.
$part->dispatch($sqlWalker), $part->dispatch($sqlWalker)
$p . ' ELSE '.
); "'".$p."'::date "
. 'END';
} else {
return 'CASE WHEN '
.' '.$part->dispatch($sqlWalker).'::date IS NOT NULL '
. 'THEN '.
$part->dispatch($sqlWalker)
. '::date ELSE '.
"'".$p."'::date "
. 'END';
} }
return sprintf(
"CASE WHEN %s::date IS NOT NULL THEN %s::date ELSE '%s'::date END",
$part->dispatch($sqlWalker),
$part->dispatch($sqlWalker),
$p
);
} }
public function parse(Parser $parser): void public function parse(\Doctrine\ORM\Query\Parser $parser)
{ {
$parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_IDENTIFIER);

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\Type; namespace Chill\MainBundle\Doctrine\Type;
use Chill\MainBundle\Doctrine\Model\Point; use Chill\MainBundle\Doctrine\Model\Point;
@@ -9,32 +7,40 @@ use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Platforms\AbstractPlatform;
use Chill\MainBundle\Doctrine\Model\PointException; use Chill\MainBundle\Doctrine\Model\PointException;
/** /**
* A Type for Doctrine to implement the Geography Point type * A Type for Doctrine to implement the Geography Point type
* implemented by Postgis on postgis+postgresql databases * implemented by Postgis on postgis+postgresql databases
*
*/ */
class PointType extends Type class PointType extends Type {
{
public const POINT = 'point'; const POINT = 'point';
/** /**
*
* @param array $fieldDeclaration
* @param AbstractPlatform $platform
* @return string * @return string
*/ */
public function getSQLDeclaration(array $column, AbstractPlatform $platform) public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{ {
return 'geometry(POINT,'.Point::$SRID.')'; return 'geometry(POINT,'.Point::$SRID.')';
} }
/** /**
*
* @param type $value
* @param AbstractPlatform $platform
* @return ?Point * @return ?Point
*/ */
public function convertToPHPValue($value, AbstractPlatform $platform) public function convertToPHPValue($value, AbstractPlatform $platform)
{ {
if ($value === NULL){ if ($value === NULL){
return NULL; return NULL;
} else {
return Point::fromGeoJson($value);
} }
return Point::fromGeoJson($value);
} }
public function getName() public function getName()
@@ -46,9 +52,9 @@ class PointType extends Type
{ {
if ($value === NULL){ if ($value === NULL){
return NULL; return NULL;
} else {
return $value->toWKT();
} }
return $value->toWKT();
} }
public function canRequireSQLConversion() public function canRequireSQLConversion()

View File

@@ -23,11 +23,12 @@ namespace Chill\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Symfony\Component\Serializer\Annotation as Serializer;
/** /**
* @ORM\Entity * @ORM\Entity
* @ORM\Table(name="centers") * @ORM\Table(name="centers")
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
class Center implements HasCenterInterface class Center implements HasCenterInterface
{ {
@@ -45,9 +46,8 @@ class Center implements HasCenterInterface
* @var string * @var string
* *
* @ORM\Column(type="string", length=255) * @ORM\Column(type="string", length=255)
* @Serializer\Groups({"docgen:read"})
*/ */
private string $name = ''; private $name;
/** /**
* @var Collection * @var Collection

View File

@@ -1,6 +1,22 @@
<?php <?php
declare(strict_types=1); /*
* Chill is a suite of a modules, Chill is a software for social workers
* Copyright (C) 2014, Champs Libres Cooperative SCRLFS, <http://www.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\Entity; namespace Chill\MainBundle\Entity;
@@ -12,29 +28,37 @@ use Doctrine\Common\Collections\ArrayCollection;
* @ORM\Entity * @ORM\Entity
* @ORM\Table(name="role_scopes") * @ORM\Table(name="role_scopes")
* @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region") * @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region")
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
class RoleScope class RoleScope
{ {
/** /**
* @var integer
*
* @ORM\Id * @ORM\Id
* @ORM\Column(name="id", type="integer") * @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO") * @ORM\GeneratedValue(strategy="AUTO")
*/ */
private ?int $id = null; private $id;
/** /**
* @var string
*
* @ORM\Column(type="string", length=255) * @ORM\Column(type="string", length=255)
*/ */
private ?string $role = null; private $role;
/** /**
* @var Scope
*
* @ORM\ManyToOne( * @ORM\ManyToOne(
* targetEntity="Chill\MainBundle\Entity\Scope", * targetEntity="Chill\MainBundle\Entity\Scope",
* inversedBy="roleScopes") * inversedBy="roleScopes")
* @ORM\JoinColumn(nullable=true, name="scope_id") * @ORM\JoinColumn(nullable=true, name="scope_id")
* @ORM\Cache(usage="NONSTRICT_READ_WRITE") * @ORM\Cache(usage="NONSTRICT_READ_WRITE")
*/ */
private ?Scope $scope = null; private $scope;
/** /**
* @var Collection * @var Collection
@@ -45,33 +69,55 @@ class RoleScope
*/ */
private $permissionsGroups; private $permissionsGroups;
/**
* RoleScope constructor.
*/
public function __construct() { public function __construct() {
$this->new = true;
$this->permissionsGroups = new ArrayCollection(); $this->permissionsGroups = new ArrayCollection();
} }
public function getId(): ?int /**
* @return int
*/
public function getId()
{ {
return $this->id; return $this->id;
} }
public function getRole(): ?string /**
* @return string
*/
public function getRole()
{ {
return $this->role; return $this->role;
} }
public function getScope(): ?Scope /**
* @return Scope
*/
public function getScope()
{ {
return $this->scope; return $this->scope;
} }
public function setRole(?string $role = null): self /**
* @param type $role
* @return RoleScope
*/
public function setRole($role)
{ {
$this->role = $role; $this->role = $role;
return $this; return $this;
} }
public function setScope(?Scope $scope = null): self /**
* @param Scope $scope
* @return RoleScope
*/
public function setScope(Scope $scope = null)
{ {
$this->scope = $scope; $this->scope = $scope;

View File

@@ -8,7 +8,7 @@ use Doctrine\Common\Collections\ArrayCollection;
use Chill\MainBundle\Entity\UserJob; use Chill\MainBundle\Entity\UserJob;
use Symfony\Component\Security\Core\User\AdvancedUserInterface; use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
/** /**
* User * User
@@ -16,7 +16,7 @@ use Symfony\Component\Serializer\Annotation as Serializer;
* @ORM\Entity * @ORM\Entity
* @ORM\Table(name="users") * @ORM\Table(name="users")
* @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region") * @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region")
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={ * @DiscriminatorMap(typeProperty="type", mapping={
* "user"=User::class * "user"=User::class
* }) * })
*/ */
@@ -51,7 +51,6 @@ class User implements AdvancedUserInterface {
/** /**
* @ORM\Column(type="string", length=200) * @ORM\Column(type="string", length=200)
* @Serializer\Groups({"docgen:read"})
*/ */
private string $label = ''; private string $label = '';
@@ -59,9 +58,8 @@ class User implements AdvancedUserInterface {
* @var string * @var string
* *
* @ORM\Column(type="string", length=150, nullable=true) * @ORM\Column(type="string", length=150, nullable=true)
* @Serializer\Groups({"docgen:read"})
*/ */
private ?string $email = null; private $email;
/** /**
* @var string * @var string
@@ -125,7 +123,6 @@ class User implements AdvancedUserInterface {
/** /**
* @var Center|null * @var Center|null
* @ORM\ManyToOne(targetEntity=Center::class) * @ORM\ManyToOne(targetEntity=Center::class)
* @Serializer\Groups({"docgen:read"})
*/ */
private ?Center $mainCenter = null; private ?Center $mainCenter = null;

View File

@@ -1,25 +1,48 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2016 Champs-Libres <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\Export\Formatter; namespace Chill\MainBundle\Export\Formatter;
use Symfony\Component\Form\FormBuilderInterface; use Chill\MainBundle\Export\ExportInterface;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Export\FormatterInterface; use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Export\ExportManager; use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// command to get the report with curl : curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff
/** /**
* Command to get the report with curl: *
* curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff *
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @deprecated this formatter is not used any more. * @deprecated this formatter is not used any more.
*/ */
class CSVFormatter implements FormatterInterface class CSVFormatter implements FormatterInterface
{ {
protected TranslatorInterface $translator; /**
*
* @var TranslatorInterface
*/
protected $translator;
protected $result; protected $result;
@@ -62,7 +85,11 @@ class CSVFormatter implements FormatterInterface
} }
/** /**
*
* @uses appendAggregatorForm * @uses appendAggregatorForm
* @param FormBuilderInterface $builder
* @param type $exportAlias
* @param array $aggregatorAliases
*/ */
public function buildForm(FormBuilderInterface $builder, $exportAlias, array $aggregatorAliases) public function buildForm(FormBuilderInterface $builder, $exportAlias, array $aggregatorAliases)
{ {
@@ -145,35 +172,20 @@ class CSVFormatter implements FormatterInterface
* If two aggregators have the same order, the second given will be placed * If two aggregators have the same order, the second given will be placed
* after. This is not significant for the first ordering. * after. This is not significant for the first ordering.
* *
* @param type $formatterData
* @return type
*/ */
protected function orderingHeaders(array $formatterData) protected function orderingHeaders($formatterData)
{ {
$this->formatterData = $formatterData; $this->formatterData = $formatterData;
uasort( uasort($this->formatterData, function($a, $b) {
$this->formatterData,
static fn(array $a, array $b): int => ($a['order'] <= $b['order'] ? -1 : 1)
);
}
private function findColumnPosition(&$columnHeaders, $columnToFind): int return ($a['order'] <= $b['order'] ? -1 : 1);
{ });
$i = 0;
foreach($columnHeaders as $set) {
if ($set === $columnToFind) {
return $i;
}
$i++;
}
//we didn't find it, adding the column
$columnHeaders[] = $columnToFind;
return $i++;
} }
protected function generateContent() protected function generateContent()
{ {
$line = null;
$rowKeysNb = count($this->getRowHeaders()); $rowKeysNb = count($this->getRowHeaders());
$columnKeysNb = count($this->getColumnHeaders()); $columnKeysNb = count($this->getColumnHeaders());
$resultsKeysNb = count($this->export->getQueryKeys($this->exportData)); $resultsKeysNb = count($this->export->getQueryKeys($this->exportData));
@@ -184,6 +196,21 @@ class CSVFormatter implements FormatterInterface
$contentData = array(); $contentData = array();
$content = array(); $content = array();
function findColumnPosition(&$columnHeaders, $columnToFind) {
$i = 0;
foreach($columnHeaders as $set) {
if ($set === $columnToFind) {
return $i;
}
$i++;
}
//we didn't find it, adding the column
$columnHeaders[] = $columnToFind;
return $i++;
}
// create a file pointer connected to the output stream // create a file pointer connected to the output stream
$output = fopen('php://output', 'w'); $output = fopen('php://output', 'w');
@@ -217,7 +244,7 @@ class CSVFormatter implements FormatterInterface
// add the column headers // add the column headers
/* @var $columns string[] the column for this row */ /* @var $columns string[] the column for this row */
$columns = array_slice($row, $rowKeysNb, $columnKeysNb); $columns = array_slice($row, $rowKeysNb, $columnKeysNb);
$columnPosition = $this->findColumnPosition($columnHeaders, $columns); $columnPosition = findColumnPosition($columnHeaders, $columns);
//fill with blank at the position given by the columnPosition + nbRowHeaders //fill with blank at the position given by the columnPosition + nbRowHeaders
for ($i=0; $i < $columnPosition; $i++) { for ($i=0; $i < $columnPosition; $i++) {

View File

@@ -229,7 +229,7 @@ class SpreadSheetFormatter implements FormatterInterface
$this->getContentType($this->formatterData['format'])); $this->getContentType($this->formatterData['format']));
$this->tempfile = \tempnam(\sys_get_temp_dir(), ''); $this->tempfile = \tempnam(\sys_get_temp_dir(), '');
$this->generateContent(); $this->generatecontent();
$f = \fopen($this->tempfile, 'r'); $f = \fopen($this->tempfile, 'r');
$response->setContent(\stream_get_contents($f)); $response->setContent(\stream_get_contents($f));

View File

@@ -1,15 +1,38 @@
<?php <?php
/*
declare(strict_types=1); * 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\Form\Type\DataTransformer; namespace Chill\MainBundle\Form\Type\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Exception\UnexpectedTypeException;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class DateIntervalTransformer implements DataTransformerInterface class DateIntervalTransformer implements DataTransformerInterface
{ {
/**
*
* @param \DateInterval $value
* @throws UnexpectedTypeException
*/
public function transform($value) public function transform($value)
{ {
if (empty($value)) { if (empty($value)) {
@@ -27,36 +50,31 @@ class DateIntervalTransformer implements DataTransformerInterface
'n' => $value->d / 7, 'n' => $value->d / 7,
'unit' => 'W' 'unit' => 'W'
]; ];
} else {
return [
'n' => $value->d,
'unit' => 'D'
];
} }
} elseif ($value->m > 0) {
return [
'n' => $value->d,
'unit' => 'D'
];
}
if ($value->m > 0) {
return [ return [
'n' => $value->m, 'n' => $value->m,
'unit' => 'M' 'unit' => 'M'
]; ];
} } elseif ($value->y > 0) {
if ($value->y > 0) {
return [ return [
'n' => $value->y, 'n' => $value->y,
'unit' => 'Y' 'unit' => 'Y'
]; ];
} }
throw new TransformationFailedException( throw new TransformationFailedException('the date interval does not '
'The date interval does not contains any days, months or years.' . 'contains any days, months or years');
);
} }
public function reverseTransform($value) public function reverseTransform($value)
{ {
if (empty($value) || empty($value['n'])) { if (empty($value) or empty($value['n'])) {
return null; return null;
} }
@@ -65,11 +83,10 @@ class DateIntervalTransformer implements DataTransformerInterface
try { try {
return new \DateInterval($string); return new \DateInterval($string);
} catch (\Exception $e) { } catch (\Exception $e) {
throw new TransformationFailedException( throw new TransformationFailedException("Could not transform value "
'Could not transform value into DateInterval', . "into DateInterval", 1542, $e);
1542,
$e
);
} }
} }
} }

View File

@@ -1,17 +1,44 @@
<?php <?php
declare(strict_types=1); /*
* Chill is a software for social workers
* Copyright (C) 2016 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\Pagination; namespace Chill\MainBundle\Pagination;
/** /**
* PageGenerator associated with a Paginator. * PageGenerator associated with a Paginator
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
*/ */
class PageGenerator implements \Iterator class PageGenerator implements \Iterator
{ {
protected Paginator $paginator; /**
*
* @var Paginator
*/
protected $paginator;
protected int $current = 1; /**
*
* @var int
*/
protected $current = 1;
public function __construct(Paginator $paginator) public function __construct(Paginator $paginator)
{ {

View File

@@ -402,11 +402,3 @@ input.belgian_national_number {
&.daily_counter {} &.daily_counter {}
&.control_digit {} &.control_digit {}
} }
// replace abbr
span.item-key {
font-variant: all-small-caps;
font-size: 90%;
background-color: #0000000a;
//text-decoration: dotted underline;
}

View File

@@ -8,43 +8,3 @@ require('./bootstrap.scss');
import Dropdown from 'bootstrap/js/src/dropdown'; import Dropdown from 'bootstrap/js/src/dropdown';
import Modal from 'bootstrap/js/dist/modal'; import Modal from 'bootstrap/js/dist/modal';
import Collapse from 'bootstrap/js/src/collapse'; import Collapse from 'bootstrap/js/src/collapse';
import Carousel from 'bootstrap/js/src/carousel';
//
// ACHeaderSlider is a small slider used in banner of AccompanyingCourse Section
// Initialize options, and show/hide controls in first/last slides
//
let ACHeaderSlider = document.querySelector('#ACHeaderSlider');
if (ACHeaderSlider) {
let controlPrev = ACHeaderSlider.querySelector('button[data-bs-slide="prev"]'),
controlNext = ACHeaderSlider.querySelector('button[data-bs-slide="next"]'),
length = ACHeaderSlider.querySelectorAll('.carousel-item').length,
last = length-1,
carousel = new Carousel(ACHeaderSlider, {
interval: false,
wrap: false,
ride: false,
keyboard: false,
touch: true
})
;
document.addEventListener('DOMContentLoaded', (e) => {
controlNext.classList.remove('visually-hidden');
});
ACHeaderSlider.addEventListener('slid.bs.carousel', (e) => {
//console.log('from slide', e.direction, e.relatedTarget, e.from, e.to );
switch (e.to) {
case 0:
controlPrev.classList.add('visually-hidden');
controlNext.classList.remove('visually-hidden');
break;
case last:
controlPrev.classList.remove('visually-hidden');
controlNext.classList.add('visually-hidden');
break;
default:
controlPrev.classList.remove('visually-hidden');
controlNext.classList.remove('visually-hidden');
}
})
}

View File

@@ -5,7 +5,7 @@
<meta http-equiv="x-ua-compatible" content="ie=edge"> <meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ installation.name }} - {% block title %}{{ 'Homepage'|trans }}{% endblock %}</title> <title>{{ installation.name }} - {% block title %}{% endblock %}</title>
<link rel="shortcut icon" href="{{ asset('build/images/favicon.ico') }}" type="image/x-icon"> <link rel="shortcut icon" href="{{ asset('build/images/favicon.ico') }}" type="image/x-icon">
{{ encore_entry_link_tags('mod_bootstrap') }} {{ encore_entry_link_tags('mod_bootstrap') }}
@@ -68,9 +68,6 @@
<button type="submit" class="btn btn-lg btn-warning mt-3"> <button type="submit" class="btn btn-lg btn-warning mt-3">
<i class="fa fa-fw fa-search"></i> {{ 'Search'|trans }} <i class="fa fa-fw fa-search"></i> {{ 'Search'|trans }}
</button> </button>
<a class="btn btn-lg btn-misc mt-3" href="{{ path('chill_main_advanced_search_list') }}">
<i class="fa fa-fw fa-search"></i> {{ 'Advanced search'|trans }}
</a>
</center> </center>
</form> </form>
</div> </div>

View File

@@ -1,6 +1,22 @@
<?php <?php
declare(strict_types=1); /*
* Chill is a software for social workers
* 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\Routing\Loader; namespace Chill\MainBundle\Routing\Loader;
@@ -12,31 +28,49 @@ use Symfony\Component\Routing\RouteCollection;
* *
* Routes must be defined in configuration, add an entry * Routes must be defined in configuration, add an entry
* under `chill_main.routing.resources` * under `chill_main.routing.resources`
*
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
class ChillRoutesLoader extends Loader class ChillRoutesLoader extends Loader
{ {
private array $routes; private $routes;
public function __construct(array $routes) public function __construct(array $routes)
{ {
$this->routes = $routes; $this->routes = $routes;
parent::__construct();
} }
/**
* {@inheritDoc}
*
* @param type $resource
* @param type $type
* @return RouteCollection
*/
public function load($resource, $type = null) public function load($resource, $type = null)
{ {
$collection = new RouteCollection(); $collection = new RouteCollection();
foreach ($this->routes as $routeResource) { foreach ($this->routes as $resource) {
$collection->addCollection( $collection->addCollection(
$this->import($routeResource, NULL) $this->import($resource, NULL)
); );
} }
return $collection; return $collection;
} }
/**
* {@inheritDoc}
*
* @param type $resource
* @param type $type
* @return boolean
*/
public function supports($resource, $type = null) public function supports($resource, $type = null)
{ {
return 'chill_routes' === $type; return 'chill_routes' === $type;

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Routing; namespace Chill\MainBundle\Routing;
use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RouteCollection;
@@ -10,6 +8,7 @@ use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface; use Knp\Menu\ItemInterface;
use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
/** /**
* This class permit to build menu from the routing information * This class permit to build menu from the routing information
* stored in each bundle. * stored in each bundle.
@@ -21,15 +20,29 @@ use Symfony\Component\Translation\TranslatorInterface;
class MenuComposer class MenuComposer
{ {
private RouterInterface $router; /**
*
* @var RouterInterface
*/
private $router;
private FactoryInterface $menuFactory; /**
*
* @var FactoryInterface
*/
private $menuFactory;
private TranslatorInterface $translator; /**
*
* @var TranslatorInterface
*/
private $translator;
private array $localMenuBuilders = []; /**
*
private RouteCollection $routeCollection; * @var
*/
private $localMenuBuilders = [];
function __construct( function __construct(

View File

@@ -78,11 +78,11 @@ abstract class AbstractSearch implements SearchInterface
$recomposed .= ' '.$term.':'; $recomposed .= ' '.$term.':';
$containsSpace = \strpos($terms[$term], " ") !== false; $containsSpace = \strpos($terms[$term], " ") !== false;
if ($containsSpace) { if ($containsSpace) {
$recomposed .= '"'; $recomposed .= "(";
} }
$recomposed .= (mb_stristr(' ', $terms[$term]) === FALSE) ? $terms[$term] : '('.$terms[$term].')'; $recomposed .= (mb_stristr(' ', $terms[$term]) === FALSE) ? $terms[$term] : '('.$terms[$term].')';
if ($containsSpace) { if ($containsSpace) {
$recomposed .= '"'; $recomposed .= ")";
} }
} }
} }

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Search; namespace Chill\MainBundle\Search;
use Chill\MainBundle\Search\Entity\SearchUserApiProvider; use Chill\MainBundle\Search\Entity\SearchUserApiProvider;
@@ -15,20 +13,27 @@ use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Chill\MainBundle\Search\SearchProvider; use Chill\MainBundle\Search\SearchProvider;
use Symfony\Component\VarDumper\Resources\functions\dump; use Symfony\Component\VarDumper\Resources\functions\dump;
/**
*/
class SearchApi class SearchApi
{ {
private EntityManagerInterface $em; private EntityManagerInterface $em;
private PaginatorFactory $paginator; private PaginatorFactory $paginator;
private iterable $providers = []; private array $providers = [];
public function __construct( public function __construct(
EntityManagerInterface $em, EntityManagerInterface $em,
iterable $providers, SearchPersonApiProvider $searchPerson,
ThirdPartyApiSearch $thirdPartyApiSearch,
SearchUserApiProvider $searchUser,
PaginatorFactory $paginator PaginatorFactory $paginator
) { )
{
$this->em = $em; $this->em = $em;
$this->providers = $providers; $this->providers[] = $searchPerson;
$this->providers[] = $thirdPartyApiSearch;
$this->providers[] = $searchUser;
$this->paginator = $paginator; $this->paginator = $paginator;
} }
@@ -64,15 +69,10 @@ class SearchApi
private function findProviders(string $pattern, array $types, array $parameters): array private function findProviders(string $pattern, array $types, array $parameters): array
{ {
$providers = []; return \array_filter(
$this->providers,
foreach ($this->providers as $provider) { fn($p) => $p->supportsTypes($pattern, $types, $parameters)
if ($provider->supportsTypes($pattern, $types, $parameters)) { );
$providers[] = $provider;
}
}
return $providers;
} }
private function countItems($providers, $types, $parameters): int private function countItems($providers, $types, $parameters): int
@@ -83,12 +83,12 @@ class SearchApi
$countNq = $this->em->createNativeQuery($countQuery, $rsmCount); $countNq = $this->em->createNativeQuery($countQuery, $rsmCount);
$countNq->setParameters($parameters); $countNq->setParameters($parameters);
return (int) $countNq->getSingleScalarResult(); return $countNq->getSingleScalarResult();
} }
private function buildCountQuery(array $queries, $types, $parameters) private function buildCountQuery(array $queries, $types, $parameters)
{ {
$query = "SELECT SUM(c) AS count FROM ({union_unordered}) AS sq"; $query = "SELECT COUNT(*) AS count FROM ({union_unordered}) AS sq";
$unions = []; $unions = [];
$parameters = []; $parameters = [];
@@ -126,7 +126,7 @@ class SearchApi
private function fetchRawResult($queries, $types, $parameters, $paginator): array private function fetchRawResult($queries, $types, $parameters, $paginator): array
{ {
list($union, $parameters) = $this->buildUnionQuery($queries, $types, $parameters); list($union, $parameters) = $this->buildUnionQuery($queries, $types, $parameters, $paginator);
$rsm = new ResultSetMappingBuilder($this->em); $rsm = new ResultSetMappingBuilder($this->em);
$rsm->addScalarResult('key', 'key', Types::STRING) $rsm->addScalarResult('key', 'key', Types::STRING)
->addScalarResult('metadata', 'metadata', Types::JSON) ->addScalarResult('metadata', 'metadata', Types::JSON)
@@ -142,20 +142,17 @@ class SearchApi
private function prepareProviders(array $rawResults) private function prepareProviders(array $rawResults)
{ {
$metadatas = []; $metadatas = [];
$providers = [];
foreach ($rawResults as $r) { foreach ($rawResults as $r) {
foreach ($this->providers as $k => $p) { foreach ($this->providers as $k => $p) {
if ($p->supportsResult($r['key'], $r['metadata'])) { if ($p->supportsResult($r['key'], $r['metadata'])) {
$metadatas[$k][] = $r['metadata']; $metadatas[$k][] = $r['metadata'];
$providers[$k] = $p;
break; break;
} }
} }
} }
foreach ($metadatas as $k => $m) { foreach ($metadatas as $k => $m) {
$providers[$k]->prepare($m); $this->providers[$k]->prepare($m);
} }
} }

View File

@@ -4,8 +4,6 @@ namespace Chill\MainBundle\Search;
class SearchApiQuery class SearchApiQuery
{ {
private array $select = [];
private array $selectParams = [];
private ?string $selectKey = null; private ?string $selectKey = null;
private array $selectKeyParams = []; private array $selectKeyParams = [];
private ?string $jsonbMetadata = null; private ?string $jsonbMetadata = null;
@@ -17,38 +15,6 @@ class SearchApiQuery
private array $whereClauses = []; private array $whereClauses = [];
private array $whereClausesParams = []; private array $whereClausesParams = [];
public function addSelectClause(string $select, array $params = []): self
{
$this->select[] = $select;
$this->selectParams = [...$this->selectParams, ...$params];
return $this;
}
public function resetSelectClause(): self
{
$this->select = [];
$this->selectParams = [];
$this->selectKey = null;
$this->selectKeyParams = [];
$this->jsonbMetadata = null;
$this->jsonbMetadataParams = [];
$this->pertinence = null;
$this->pertinenceParams = [];
return $this;
}
public function getSelectClauses(): array
{
return $this->select;
}
public function getSelectParams(): array
{
return $this->selectParams;
}
public function setSelectKey(string $selectKey, array $params = []): self public function setSelectKey(string $selectKey, array $params = []): self
{ {
$this->selectKey = $selectKey; $this->selectKey = $selectKey;
@@ -81,16 +47,6 @@ class SearchApiQuery
return $this; return $this;
} }
public function getFromClause(): string
{
return $this->fromClause;
}
public function getFromParams(): array
{
return $this->fromClauseParams;
}
/** /**
* Set the where clause and replace all existing ones. * Set the where clause and replace all existing ones.
* *
@@ -98,7 +54,7 @@ class SearchApiQuery
public function setWhereClauses(string $whereClause, array $params = []): self public function setWhereClauses(string $whereClause, array $params = []): self
{ {
$this->whereClauses = [$whereClause]; $this->whereClauses = [$whereClause];
$this->whereClausesParams = $params; $this->whereClausesParams = [$params];
return $this; return $this;
} }
@@ -115,53 +71,11 @@ class SearchApiQuery
public function andWhereClause(string $whereClause, array $params = []): self public function andWhereClause(string $whereClause, array $params = []): self
{ {
$this->whereClauses[] = $whereClause; $this->whereClauses[] = $whereClause;
\array_push($this->whereClausesParams, ...$params); $this->whereClausesParams[] = $params;
return $this; return $this;
} }
private function buildSelectParams(bool $count = false): array
{
if ($count) {
return [];
}
$args = $this->getSelectParams();
if (null !== $this->selectKey) {
$args = [...$args, ...$this->selectKeyParams];
}
if (null !== $this->jsonbMetadata) {
$args = [...$args, ...$this->jsonbMetadataParams];
}
if (null !== $this->pertinence) {
$args = [...$args, ...$this->pertinenceParams];
}
return $args;
}
private function buildSelectClause(bool $countOnly = false): string
{
if ($countOnly) {
return 'count(*) AS c';
}
$selects = $this->getSelectClauses();
if (null !== $this->selectKey) {
$selects[] = \strtr("'{key}' AS key", [ '{key}' => $this->selectKey ]);
}
if (null !== $this->jsonbMetadata) {
$selects[] = \strtr('{metadata} AS metadata', [ '{metadata}' => $this->jsonbMetadata]);
}
if (null !== $this->pertinence) {
$selects[] = \strtr('{pertinence} AS pertinence', [ '{pertinence}' => $this->pertinence]);
}
return \implode(', ', $selects);
}
public function buildQuery(bool $countOnly = false): string public function buildQuery(bool $countOnly = false): string
{ {
$isMultiple = count($this->whereClauses); $isMultiple = count($this->whereClauses);
@@ -173,8 +87,19 @@ class SearchApiQuery
($isMultiple ? ')' : '') ($isMultiple ? ')' : '')
; ;
$select = $this->buildSelectClause($countOnly); if (!$countOnly) {
$select = \strtr("
'{key}' AS key,
{metadata} AS metadata,
{pertinence} AS pertinence
", [
'{key}' => $this->selectKey,
'{metadata}' => $this->jsonbMetadata,
'{pertinence}' => $this->pertinence,
]);
} else {
$select = "1 AS c";
}
return \strtr("SELECT return \strtr("SELECT
{select} {select}
@@ -191,16 +116,18 @@ class SearchApiQuery
public function buildParameters(bool $countOnly = false): array public function buildParameters(bool $countOnly = false): array
{ {
if (!$countOnly) { if (!$countOnly) {
return [ return \array_merge(
...$this->buildSelectParams($countOnly), $this->selectKeyParams,
...$this->fromClauseParams, $this->jsonbMetadataParams,
...$this->whereClausesParams, $this->pertinenceParams,
]; $this->fromClauseParams,
\array_merge([], ...$this->whereClausesParams),
);
} else { } else {
return [ return \array_merge(
...$this->fromClauseParams, $this->fromClauseParams,
...$this->whereClausesParams, \array_merge([], ...$this->whereClausesParams),
]; );
} }
} }
} }

View File

@@ -1,7 +1,5 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Search; namespace Chill\MainBundle\Search;
use Symfony\Component\Serializer\Annotation as Serializer; use Symfony\Component\Serializer\Annotation as Serializer;
@@ -12,8 +10,6 @@ class SearchApiResult
private $result; private $result;
private float $relevance;
public function __construct(float $relevance) public function __construct(float $relevance)
{ {
$this->relevance = $relevance; $this->relevance = $relevance;

View File

@@ -121,15 +121,14 @@ class SearchProvider
private function extractTerms(&$subject) private function extractTerms(&$subject)
{ {
$terms = array(); $terms = array();
$matches = []; preg_match_all('/([a-z\-]+):([\w\-]+|\([^\(\r\n]+\))/', $subject, $matches);
preg_match_all('/([a-z\-]+):(([^"][\S\-]+)|"[^"]*")/', $subject, $matches);
foreach ($matches[2] as $key => $match) { foreach ($matches[2] as $key => $match) {
//remove from search pattern //remove from search pattern
$this->mustBeExtracted[] = $matches[0][$key]; $this->mustBeExtracted[] = $matches[0][$key];
//strip parenthesis //strip parenthesis
if (mb_substr($match, 0, 1) === '"' && if (mb_substr($match, 0, 1) === '(' &&
mb_substr($match, mb_strlen($match) - 1) === '"') { mb_substr($match, mb_strlen($match) - 1) === ')') {
$match = trim(mb_substr($match, 1, mb_strlen($match) - 2)); $match = trim(mb_substr($match, 1, mb_strlen($match) - 2));
} }
$terms[$matches[1][$key]] = $match; $terms[$matches[1][$key]] = $match;

View File

@@ -1,36 +0,0 @@
<?php
namespace Chill\MainBundle\Search\Utils;
use \DateTimeImmutable;
class ExtractDateFromPattern
{
private const DATE_PATTERN = [
["([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))", 'Y-m-d'], // 1981-05-12
["((0[1-9]|[12]\d|3[01])\/(0[1-9]|1[0-2])\/([12]\d{3}))", 'd/m/Y'], // 15/12/1980
["((0[1-9]|[12]\d|3[01])-(0[1-9]|1[0-2])-([12]\d{3}))", 'd-m-Y'], // 15/12/1980
];
public function extractDates(string $subject): SearchExtractionResult
{
$dates = [];
$filteredSubject = $subject;
foreach (self::DATE_PATTERN as [$pattern, $format]) {
$matches = [];
\preg_match_all($pattern, $filteredSubject, $matches);
foreach ($matches[0] as $match) {
$date = DateTimeImmutable::createFromFormat($format, $match);
if (false !== $date) {
$dates[] = $date;
// filter string: remove what is found
$filteredSubject = \trim(\strtr($filteredSubject, [$match => ""]));
}
}
}
return new SearchExtractionResult($filteredSubject, $dates);
}
}

View File

@@ -1,54 +0,0 @@
<?php
namespace Chill\MainBundle\Search\Utils;
class ExtractPhonenumberFromPattern
{
private const PATTERN = "([\+]{0,1}[0-9\ ]{5,})";
public function extractPhonenumber(string $subject): SearchExtractionResult
{
$matches = [];
\preg_match(self::PATTERN, $subject,$matches);
if (0 < count($matches)) {
$phonenumber = [];
$length = 0;
foreach (\str_split(\trim($matches[0])) as $key => $char) {
switch ($char) {
case '0':
$length++;
if ($key === 0) { $phonenumber[] = '+32'; }
else { $phonenumber[] = $char; }
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
$length++;
$phonenumber[] = $char;
break;
case ' ':
break;
default:
throw new \LogicException("should not match not alnum character");
}
}
if ($length > 5) {
$filtered = \trim(\strtr($subject, [$matches[0] => '']));
return new SearchExtractionResult($filtered, [\implode('', $phonenumber)] );
}
}
return new SearchExtractionResult($subject, []);
}
}

View File

@@ -1,30 +0,0 @@
<?php
namespace Chill\MainBundle\Search\Utils;
class SearchExtractionResult
{
private string $filteredSubject;
private array $found;
public function __construct(string $filteredSubject, array $found)
{
$this->filteredSubject = $filteredSubject;
$this->found = $found;
}
public function getFound(): array
{
return $this->found;
}
public function hasResult(): bool
{
return [] !== $this->found;
}
public function getFilteredSubject(): string
{
return $this->filteredSubject;
}
}

View File

@@ -1,17 +1,34 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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\Security\Authorization; namespace Chill\MainBundle\Security\Authorization;
use Symfony\Component\Security\Core\Authorization\Voter\Voter; use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/** /**
* Voter for Chill software. * Voter for Chill software.
* *
* This abstract Voter provide generic methods to handle object specific to Chill * This abstract Voter provide generic methods to handle object specific to Chill
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
abstract class AbstractChillVoter extends Voter implements ChillVoterInterface abstract class AbstractChillVoter extends Voter implements ChillVoterInterface
{ {
@@ -22,8 +39,6 @@ abstract class AbstractChillVoter extends Voter implements ChillVoterInterface
. 'getSupportedAttributes and getSupportedClasses methods.', . 'getSupportedAttributes and getSupportedClasses methods.',
E_USER_DEPRECATED); E_USER_DEPRECATED);
// @TODO: getSupportedAttributes() should be created in here and made abstract or in ChillVoterInterface.
// @TODO: getSupportedClasses() should be created in here and made abstract or in ChillVoterInterface.
return \in_array($attribute, $this->getSupportedAttributes($attribute)) return \in_array($attribute, $this->getSupportedAttributes($attribute))
&& \in_array(\get_class($subject), $this->getSupportedClasses()); && \in_array(\get_class($subject), $this->getSupportedClasses());
} }
@@ -34,7 +49,7 @@ abstract class AbstractChillVoter extends Voter implements ChillVoterInterface
. 'methods introduced by Symfony 3.0, and do not rely on ' . 'methods introduced by Symfony 3.0, and do not rely on '
. 'isGranted method', E_USER_DEPRECATED); . 'isGranted method', E_USER_DEPRECATED);
// @TODO: isGranted() should be created in here and made abstract or in ChillVoterInterface.
return $this->isGranted($attribute, $subject, $token->getUser()); return $this->isGranted($attribute, $subject, $token->getUser());
} }
} }

View File

@@ -1,6 +1,21 @@
<?php <?php
declare(strict_types=1); /*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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\Security\Authorization; namespace Chill\MainBundle\Security\Authorization;
@@ -23,12 +38,12 @@ use Chill\MainBundle\Security\RoleProvider;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Chill\MainBundle\Entity\GroupCenter; use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\RoleScope; use Chill\MainBundle\Entity\RoleScope;
use Symfony\Component\Security\Core\User\UserInterface;
/** /**
* Helper for authorizations. * Helper for authorizations.
* *
* Provides methods for user and entities information. * Provides methods for user and entities information.
*
*/ */
class AuthorizationHelper implements AuthorizationHelperInterface class AuthorizationHelper implements AuthorizationHelperInterface
{ {
@@ -59,7 +74,11 @@ class AuthorizationHelper implements AuthorizationHelperInterface
/** /**
* Determines if a user is active on this center * Determines if a user is active on this center
* *
* If
*
* @param User $user
* @param Center|Center[] $center May be an array of center * @param Center|Center[] $center May be an array of center
* @return bool
*/ */
public function userCanReachCenter(User $user, $center): bool public function userCanReachCenter(User $user, $center): bool
{ {
@@ -70,9 +89,7 @@ class AuthorizationHelper implements AuthorizationHelperInterface
} }
} }
return false; return false;
} } elseif ($center instanceof Center) {
if ($center instanceof Center) {
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;
@@ -82,16 +99,12 @@ class AuthorizationHelper implements AuthorizationHelperInterface
return false; return false;
} }
throw new \UnexpectedValueException( throw new \UnexpectedValueException(sprintf("The entity given is not an ".
sprintf( "instance of %s, %s given", Center::class, get_class($center)));
'The entity given is not an instance of %s, %s given',
Center::class,
get_class($center)
)
);
} }
/** /**
*
* 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,
@@ -146,21 +159,19 @@ class AuthorizationHelper implements AuthorizationHelperInterface
if ($this->scopeResolverDispatcher->isConcerned($entity)) { if ($this->scopeResolverDispatcher->isConcerned($entity)) {
$scope = $this->scopeResolverDispatcher->resolveScope($entity); $scope = $this->scopeResolverDispatcher->resolveScope($entity);
if (NULL === $scope) { if (NULL === $scope) {
return true; return true;
} } elseif (is_iterable($scope)) {
foreach ($scope as $s) {
if (is_iterable($scope)) { if ($s === $roleScope->getScope()) {
foreach ($scope as $s) { return true;
if ($s === $roleScope->getScope()) { }
return true; }
} } else {
} if ($scope === $roleScope->getScope()) {
} else { return true;
if ($scope === $roleScope->getScope()) { }
return true; }
}
}
} else { } else {
return true; return true;
} }
@@ -179,11 +190,14 @@ class AuthorizationHelper implements AuthorizationHelperInterface
/** /**
* Get reachable Centers for the given user, role, * Get reachable Centers for the given user, role,
* and optionally Scope * and optionnaly Scope
* *
* @param User $user
* @param string|Role $role
* @param null|Scope $scope
* @return Center[]|array * @return Center[]|array
*/ */
public function getReachableCenters(UserInterface $user, string $role, ?Scope $scope = null): array public function getReachableCenters(User $user, string $role, ?Scope $scope = null): array
{ {
if ($role instanceof Role) { if ($role instanceof Role) {
$role = $role->getRole(); $role = $role->getRole();
@@ -199,11 +213,11 @@ class AuthorizationHelper implements AuthorizationHelperInterface
if ($scope === null) { if ($scope === null) {
$centers[] = $groupCenter->getCenter(); $centers[] = $groupCenter->getCenter();
break 1; break 1;
} } else {
if ($scope->getId() == $roleScope->getScope()->getId()){
if ($scope->getId() == $roleScope->getScope()->getId()){ $centers[] = $groupCenter->getCenter();
$centers[] = $groupCenter->getCenter(); break 1;
break 1; }
} }
} }
} }
@@ -229,7 +243,7 @@ class AuthorizationHelper implements AuthorizationHelperInterface
} }
foreach ($centers as $center) { foreach ($centers as $center) {
if ($this->userCanReachCenter($user, $center)) { if ($this->userCanReachCenter($user, $center, $role)) {
$results[] = $center; $results[] = $center;
} }
} }
@@ -242,10 +256,12 @@ class AuthorizationHelper implements AuthorizationHelperInterface
* *
* @deprecated Use getReachableCircles * @deprecated Use getReachableCircles
* *
* @param User $user
* @param string role
* @param Center|Center[] $center * @param Center|Center[] $center
* @return Scope[]|array * @return Scope[]|array
*/ */
public function getReachableScopes(UserInterface $user, string $role, $center): array public function getReachableScopes(User $user, string $role, $center): array
{ {
if ($role instanceof Role) { if ($role instanceof Role) {
$role = $role->getRole(); $role = $role->getRole();
@@ -257,11 +273,12 @@ class AuthorizationHelper implements AuthorizationHelperInterface
/** /**
* 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 string|Role $role * @param string|Role $role
* @param Center|Center[] $center * @param Center|Center[] $center
* @return Scope[] * @return Scope[]
*/ */
public function getReachableCircles(UserInterface $user, $role, $center) public function getReachableCircles(User $user, $role, $center)
{ {
$scopes = []; $scopes = [];

View File

@@ -4,23 +4,29 @@ namespace Chill\MainBundle\Security\Authorization;
use Chill\MainBundle\Entity\Center; use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Scope; use Chill\MainBundle\Entity\Scope;
use Symfony\Component\Security\Core\User\UserInterface; use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Role\Role;
interface AuthorizationHelperInterface interface AuthorizationHelperInterface
{ {
/** /**
* 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 string|Role $role
* @param null|Scope $scope * @param null|Scope $scope
* @return Center[] * @return Center[]
*/ */
public function getReachableCenters(UserInterface $user, string $role, ?Scope $scope = null): array; public function getReachableCenters(User $user, string $role, ?Scope $scope = null): array;
/** /**
* @param User $user
* @param string $role
* @param Center|Center[]|array $center * @param Center|Center[]|array $center
* @return array * @return array
*/ */
public function getReachableScopes(UserInterface $user, string $role, $center): array; public function getReachableScopes(User $user, string $role, $center): array;
} }

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