cs: Fix code style (safe rules only).

This commit is contained in:
Pol Dellaiera
2021-11-23 14:06:38 +01:00
parent 149d7ce991
commit 8f96a1121d
1223 changed files with 65199 additions and 64625 deletions

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;

View File

@@ -1,21 +1,10 @@
<?php
/*
/**
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Controller;
@@ -24,9 +13,7 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class AdminController
* Controller for the event configuration section (in admin section)
*
* @package Chill\EventBundle\Controller
* Controller for the event configuration section (in admin section).
*/
class AdminController extends AbstractController
{
@@ -37,7 +24,7 @@ class AdminController extends AbstractController
{
return $this->render('ChillEventBundle:Admin:layout.html.twig');
}
/**
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
@@ -45,4 +32,4 @@ class AdminController extends AbstractController
{
return $this->redirectToRoute('chill_main_admin_central');
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,39 +1,28 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Controller;
use Chill\EventBundle\Entity\EventType;
use Chill\EventBundle\Form\EventTypeType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Chill\EventBundle\Entity\EventType;
use Chill\EventBundle\Form\EventTypeType;
/**
* Class EventTypeController
*
* @package Chill\EventBundle\Controller
* Class EventTypeController.
*/
class EventTypeController extends AbstractController
{
/**
* Lists all EventType entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillEventBundle:EventType')->findAll();
return $this->render('ChillEventBundle:EventType:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new EventType entity.
*
*/
public function createAction(Request $request)
{
@@ -46,149 +35,22 @@ class EventTypeController extends AbstractController
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('chill_eventtype_admin',
array('id' => $entity->getId())));
return $this->redirect($this->generateUrl(
'chill_eventtype_admin',
['id' => $entity->getId()]
));
}
return $this->render('ChillEventBundle:EventType:new.html.twig', array(
return $this->render('ChillEventBundle:EventType:new.html.twig', [
'entity' => $entity,
'form' => $form->createView(),
));
'form' => $form->createView(),
]);
}
/**
* Creates a form to create a EventType entity.
*
* @param EventType $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(EventType $entity)
{
$form = $this->createForm(EventTypeType::class, $entity, array(
'action' => $this->generateUrl('chill_eventtype_admin_create'),
'method' => 'POST',
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new EventType entity.
*
*/
public function newAction()
{
$entity = new EventType();
$form = $this->createCreateForm($entity);
return $this->render('ChillEventBundle:EventType:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a EventType entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:EventType')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EventType entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:EventType:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing EventType entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:EventType')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EventType entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:EventType:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a EventType entity.
*
* @param EventType $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(EventType $entity)
{
$form = $this->createForm(EventTypeType::class, $entity, array(
'action' => $this->generateUrl('chill_eventtype_admin_update',
array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing EventType entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:EventType')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EventType entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('chill_eventtype_admin',
array('id' => $id)));
}
return $this->render('ChillEventBundle:EventType:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a EventType entity.
*
* @param mixed $id
*/
public function deleteAction(Request $request, $id)
{
@@ -210,6 +72,136 @@ class EventTypeController extends AbstractController
return $this->redirect($this->generateUrl('chill_eventtype_admin'));
}
/**
* Displays a form to edit an existing EventType entity.
*
* @param mixed $id
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:EventType')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EventType entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:EventType:edit.html.twig', [
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Lists all EventType entities.
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillEventBundle:EventType')->findAll();
return $this->render('ChillEventBundle:EventType:index.html.twig', [
'entities' => $entities,
]);
}
/**
* Displays a form to create a new EventType entity.
*/
public function newAction()
{
$entity = new EventType();
$form = $this->createCreateForm($entity);
return $this->render('ChillEventBundle:EventType:new.html.twig', [
'entity' => $entity,
'form' => $form->createView(),
]);
}
/**
* Finds and displays a EventType entity.
*
* @param mixed $id
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:EventType')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EventType entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:EventType:show.html.twig', [
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Edits an existing EventType entity.
*
* @param mixed $id
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:EventType')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find EventType entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl(
'chill_eventtype_admin',
['id' => $id]
));
}
return $this->render('ChillEventBundle:EventType:edit.html.twig', [
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Creates a form to create a EventType entity.
*
* @param EventType $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(EventType $entity)
{
$form = $this->createForm(EventTypeType::class, $entity, [
'action' => $this->generateUrl('chill_eventtype_admin_create'),
'method' => 'POST',
]);
$form->add('submit', SubmitType::class, ['label' => 'Create']);
return $form;
}
/**
* Creates a form to delete a EventType entity by id.
*
@@ -220,11 +212,34 @@ class EventTypeController extends AbstractController
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('chill_eventtype_admin_delete',
array('id' => $id)))
->setAction($this->generateUrl(
'chill_eventtype_admin_delete',
['id' => $id]
))
->setMethod('DELETE')
->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm()
;
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
}
/**
* Creates a form to edit a EventType entity.
*
* @param EventType $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(EventType $entity)
{
$form = $this->createForm(EventTypeType::class, $entity, [
'action' => $this->generateUrl(
'chill_eventtype_admin_update',
['id' => $entity->getId()]
),
'method' => 'PUT',
]);
$form->add('submit', SubmitType::class, ['label' => 'Update']);
return $form;
}
}

View File

@@ -1,38 +1,27 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Controller;
use Chill\EventBundle\Entity\Role;
use Chill\EventBundle\Form\RoleType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Chill\EventBundle\Entity\Role;
use Chill\EventBundle\Form\RoleType;
/**
* Class RoleController
*
* @package Chill\EventBundle\Controller
* Class RoleController.
*/
class RoleController extends AbstractController
{
/**
* Lists all Role entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillEventBundle:Role')->findAll();
return $this->render('ChillEventBundle:Role:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Role entity.
*
*/
public function createAction(Request $request)
{
@@ -45,149 +34,22 @@ class RoleController extends AbstractController
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('chill_event_admin_role',
array('id' => $entity->getId())));
return $this->redirect($this->generateUrl(
'chill_event_admin_role',
['id' => $entity->getId()]
));
}
return $this->render('ChillEventBundle:Role:new.html.twig', array(
return $this->render('ChillEventBundle:Role:new.html.twig', [
'entity' => $entity,
'form' => $form->createView(),
));
'form' => $form->createView(),
]);
}
/**
* Creates a form to create a Role entity.
*
* @param Role $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Role $entity)
{
$form = $this->createForm(RoleType::class, $entity, array(
'action' => $this->generateUrl('chill_event_admin_role_create'),
'method' => 'POST',
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Role entity.
*
*/
public function newAction()
{
$entity = new Role();
$form = $this->createCreateForm($entity);
return $this->render('ChillEventBundle:Role:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Role entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Role')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Role entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Role:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Role entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Role')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Role entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Role:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a Role entity.
*
* @param Role $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Role $entity)
{
$form = $this->createForm(RoleType::class, $entity, array(
'action' => $this->generateUrl('chill_event_admin_role_update',
array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Role entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Role')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Role entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('chill_event_admin_role',
array('id' => $id)));
}
return $this->render('ChillEventBundle:Role:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Role entity.
*
* @param mixed $id
*/
public function deleteAction(Request $request, $id)
{
@@ -209,6 +71,136 @@ class RoleController extends AbstractController
return $this->redirect($this->generateUrl('chill_event_admin_role'));
}
/**
* Displays a form to edit an existing Role entity.
*
* @param mixed $id
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Role')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Role entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Role:edit.html.twig', [
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Lists all Role entities.
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillEventBundle:Role')->findAll();
return $this->render('ChillEventBundle:Role:index.html.twig', [
'entities' => $entities,
]);
}
/**
* Displays a form to create a new Role entity.
*/
public function newAction()
{
$entity = new Role();
$form = $this->createCreateForm($entity);
return $this->render('ChillEventBundle:Role:new.html.twig', [
'entity' => $entity,
'form' => $form->createView(),
]);
}
/**
* Finds and displays a Role entity.
*
* @param mixed $id
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Role')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Role entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Role:show.html.twig', [
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Edits an existing Role entity.
*
* @param mixed $id
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Role')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Role entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl(
'chill_event_admin_role',
['id' => $id]
));
}
return $this->render('ChillEventBundle:Role:edit.html.twig', [
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Creates a form to create a Role entity.
*
* @param Role $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Role $entity)
{
$form = $this->createForm(RoleType::class, $entity, [
'action' => $this->generateUrl('chill_event_admin_role_create'),
'method' => 'POST',
]);
$form->add('submit', SubmitType::class, ['label' => 'Create']);
return $form;
}
/**
* Creates a form to delete a Role entity by id.
*
@@ -219,10 +211,31 @@ class RoleController extends AbstractController
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('chill_event_admin_role_delete', array('id' => $id)))
->setAction($this->generateUrl('chill_event_admin_role_delete', ['id' => $id]))
->setMethod('DELETE')
->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm()
;
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
}
/**
* Creates a form to edit a Role entity.
*
* @param Role $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Role $entity)
{
$form = $this->createForm(RoleType::class, $entity, [
'action' => $this->generateUrl(
'chill_event_admin_role_update',
['id' => $entity->getId()]
),
'method' => 'PUT',
]);
$form->add('submit', SubmitType::class, ['label' => 'Update']);
return $form;
}
}

View File

@@ -1,39 +1,28 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Controller;
use Chill\EventBundle\Entity\Status;
use Chill\EventBundle\Form\StatusType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Chill\EventBundle\Entity\Status;
use Chill\EventBundle\Form\StatusType;
/**
* Class StatusController
*
* @package Chill\EventBundle\Controller
* Class StatusController.
*/
class StatusController extends AbstractController
{
/**
* Lists all Status entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillEventBundle:Status')->findAll();
return $this->render('ChillEventBundle:Status:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Status entity.
*
*/
public function createAction(Request $request)
{
@@ -46,146 +35,19 @@ class StatusController extends AbstractController
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('chill_event_admin_status', array('id' => $entity->getId())));
return $this->redirect($this->generateUrl('chill_event_admin_status', ['id' => $entity->getId()]));
}
return $this->render('ChillEventBundle:Status:new.html.twig', array(
return $this->render('ChillEventBundle:Status:new.html.twig', [
'entity' => $entity,
'form' => $form->createView(),
));
'form' => $form->createView(),
]);
}
/**
* Creates a form to create a Status entity.
*
* @param Status $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Status $entity)
{
$form = $this->createForm(StatusType::class, $entity, array(
'action' => $this->generateUrl('chill_event_admin_status_create'),
'method' => 'POST',
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Status entity.
*
*/
public function newAction()
{
$entity = new Status();
$form = $this->createCreateForm($entity);
return $this->render('ChillEventBundle:Status:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Status entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Status')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Status entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Status:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Status entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Status')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Status entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Status:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a Status entity.
*
* @param Status $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Status $entity)
{
$form = $this->createForm(StatusType::class, $entity, array(
'action' => $this->generateUrl('chill_event_admin_status_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Status entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Status')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Status entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('chill_event_admin_status', array('id' => $id)));
}
return $this->render('ChillEventBundle:Status:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Status entity.
*
* @param mixed $id
*/
public function deleteAction(Request $request, $id)
{
@@ -207,6 +69,133 @@ class StatusController extends AbstractController
return $this->redirect($this->generateUrl('chill_event_admin_status'));
}
/**
* Displays a form to edit an existing Status entity.
*
* @param mixed $id
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Status')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Status entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Status:edit.html.twig', [
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Lists all Status entities.
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillEventBundle:Status')->findAll();
return $this->render('ChillEventBundle:Status:index.html.twig', [
'entities' => $entities,
]);
}
/**
* Displays a form to create a new Status entity.
*/
public function newAction()
{
$entity = new Status();
$form = $this->createCreateForm($entity);
return $this->render('ChillEventBundle:Status:new.html.twig', [
'entity' => $entity,
'form' => $form->createView(),
]);
}
/**
* Finds and displays a Status entity.
*
* @param mixed $id
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Status')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Status entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('ChillEventBundle:Status:show.html.twig', [
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Edits an existing Status entity.
*
* @param mixed $id
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ChillEventBundle:Status')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Status entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('chill_event_admin_status', ['id' => $id]));
}
return $this->render('ChillEventBundle:Status:edit.html.twig', [
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
]);
}
/**
* Creates a form to create a Status entity.
*
* @param Status $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Status $entity)
{
$form = $this->createForm(StatusType::class, $entity, [
'action' => $this->generateUrl('chill_event_admin_status_create'),
'method' => 'POST',
]);
$form->add('submit', SubmitType::class, ['label' => 'Create']);
return $form;
}
/**
* Creates a form to delete a Status entity by id.
*
@@ -217,10 +206,28 @@ class StatusController extends AbstractController
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('chill_event_admin_status_delete', array('id' => $id)))
->setAction($this->generateUrl('chill_event_admin_status_delete', ['id' => $id]))
->setMethod('DELETE')
->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm()
;
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
}
/**
* Creates a form to edit a Status entity.
*
* @param Status $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Status $entity)
{
$form = $this->createForm(StatusType::class, $entity, [
'action' => $this->generateUrl('chill_event_admin_status_update', ['id' => $entity->getId()]),
'method' => 'PUT',
]);
$form->add('submit', SubmitType::class, ['label' => 'Update']);
return $form;
}
}

View File

@@ -1,25 +1,28 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Chill\EventBundle\Entity\EventType;
use Chill\EventBundle\Entity\Role;
use Chill\EventBundle\Entity\Status;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
/**
* Load a set of `EventType`, their `Role` and `Status`.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
*/
class LoadEventTypes extends AbstractFixture implements OrderedFixtureInterface
{
public static $refs = array();
public static $refs = [];
public function getOrder()
{
return 30000;
@@ -31,256 +34,224 @@ class LoadEventTypes extends AbstractFixture implements OrderedFixtureInterface
* Echange de savoirs
*/
$type = (new EventType())
->setActive(true)
->setName(array('fr' => 'Échange de savoirs', 'en' => 'Exchange of knowledge'))
;
->setActive(true)
->setName(['fr' => 'Échange de savoirs', 'en' => 'Exchange of knowledge']);
$manager->persist($type);
$this->addReference('event_type_knowledge', $type);
self::$refs[] = 'event_type_knowledge';
$role = (new Role())
->setActive(true)
->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'))
->setType($type)
;
->setActive(true)
->setName(['fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'])
->setType($type);
$manager->persist($role);
$role = (new Role())
->setActive(true)
->setName(array('fr' => 'Animateur'))
->setType($type);
->setActive(true)
->setName(['fr' => 'Animateur'])
->setType($type);
$manager->persist($role);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Inscrit'))
->setType($type);
->setActive(true)
->setName(['fr' => 'Inscrit'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Présent'))
->setType($type)
;
->setActive(true)
->setName(['fr' => 'Présent'])
->setType($type);
$manager->persist($status);
/*
* Formation
*/
$type = (new EventType())
->setActive(true)
->setName(array('fr' => 'Formation', 'en' => 'Course', 'nl' => 'Opleiding'))
;
->setActive(true)
->setName(['fr' => 'Formation', 'en' => 'Course', 'nl' => 'Opleiding']);
$manager->persist($type);
$this->addReference('event_type_course', $type);
self::$refs[] = 'event_type_course';
$role = (new Role())
->setActive(true)
->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'))
->setType($type)
;
->setActive(true)
->setName(['fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'])
->setType($type);
$manager->persist($role);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Inscrit'))
->setType($type)
;
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'En liste d\'attente'))
->setType($type)
;
->setName(['fr' => 'Inscrit'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(['fr' => 'En liste d\'attente'])
->setType($type);
$manager->persist($status);
/*
* Visite
*/
$type = (new EventType())
->setActive(true)
->setName(array('fr' => 'Visite', 'en' => 'Visit'))
;
->setName(['fr' => 'Visite', 'en' => 'Visit']);
$manager->persist($type);
$this->addReference('event_type_visit', $type);
self::$refs[] = 'event_type_visit';
$role = (new Role())
->setActive(true)
->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'))
->setType($type)
;
->setName(['fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'])
->setType($type);
$manager->persist($role);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Présent'))
->setType($type)
;
->setName(['fr' => 'Présent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Absent'))
->setType($type)
;
->setName(['fr' => 'Absent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Excusé'))
->setType($type)
;
->setName(['fr' => 'Excusé'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Inscrit'))
->setType($type)
;
->setName(['fr' => 'Inscrit'])
->setType($type);
$manager->persist($status);
/*
* Réunion
*/
$type = (new EventType())
->setActive(true)
->setName(array('fr' => 'Réunion', 'en' => 'Meeting'))
;
->setName(['fr' => 'Réunion', 'en' => 'Meeting']);
$manager->persist($type);
$this->addReference('event_type_meeting', $type);
self::$refs[] = 'event_type_meeting';
$role = (new Role())
->setActive(true)
->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'))
->setType($type)
;
->setName(['fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'])
->setType($type);
$manager->persist($role);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Présent'))
->setType($type)
;
->setName(['fr' => 'Présent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Absent'))
->setType($type)
;
->setName(['fr' => 'Absent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Excusé'))
->setType($type)
;
->setName(['fr' => 'Excusé'])
->setType($type);
$manager->persist($status);
/*
* Atelier
*/
$type = (new EventType())
->setActive(true)
->setName(array('fr' => 'Atelier', 'en' => 'Workshop'))
;
->setName(['fr' => 'Atelier', 'en' => 'Workshop']);
$manager->persist($type);
$this->addReference('event_type_workshop', $type);
self::$refs[] = 'event_type_workshop';
$role = (new Role())
->setActive(true)
->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'))
->setType($type)
;
->setName(['fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'])
->setType($type);
$manager->persist($role);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Présent'))
->setType($type)
;
->setName(['fr' => 'Présent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Absent'))
->setType($type)
;
->setName(['fr' => 'Absent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Excusé'))
->setType($type)
;
->setName(['fr' => 'Excusé'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Inscrit'))
->setType($type)
;
->setName(['fr' => 'Inscrit'])
->setType($type);
$manager->persist($status);
/*
* Séance d'info
*/
$type = (new EventType())
->setActive(true)
->setName(array('fr' => "Séance d'info", 'en' => 'Info'))
;
->setName(['fr' => "Séance d'info", 'en' => 'Info']);
$manager->persist($type);
$this->addReference('event_type_info', $type);
self::$refs[] = 'event_type_info';
$role = (new Role())
->setActive(true)
->setName(array('fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'))
->setType($type)
;
->setName(['fr' => 'Participant', 'nl' => 'Deelneemer', 'en' => 'Participant'])
->setType($type);
$manager->persist($role);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Présent'))
->setType($type)
;
->setName(['fr' => 'Présent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Absent'))
->setType($type)
;
->setName(['fr' => 'Absent'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Excusé'))
->setType($type)
;
->setName(['fr' => 'Excusé'])
->setType($type);
$manager->persist($status);
$status = (new Status())
->setActive(true)
->setName(array('fr' => 'Inscrit'))
->setType($type)
;
->setName(['fr' => 'Inscrit'])
->setType($type);
$manager->persist($status);
$manager->flush();
}
}

View File

@@ -1,34 +1,60 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Chill\EventBundle\Entity\Participation;
use Chill\MainBundle\Entity\Center;
use Chill\EventBundle\Entity\Event;
use Chill\EventBundle\Entity\Participation;
use Chill\MainBundle\DataFixtures\ORM\LoadScopes;
use Chill\MainBundle\Entity\Center;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
/**
* Load Events and Participation
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
* Load Events and Participation.
*/
class LoadParticipation extends AbstractFixture implements OrderedFixtureInterface
{
/**
*
* @var \Faker\Generator
*/
protected $faker;
public function __construct()
{
$this->faker = \Faker\Factory::create('fr_FR');
}
public function createEvents(Center $center, ObjectManager $manager)
{
$expectedNumber = 20;
$events = [];
for ($i = 0; $i < $expectedNumber; ++$i) {
$event = (new Event())
->setDate($this->faker->dateTimeBetween('-2 years', '+6 months'))
->setName($this->faker->words(rand(2, 4), true))
->setType($this->getReference(LoadEventTypes::$refs[array_rand(LoadEventTypes::$refs)]))
->setCenter($center)
->setCircle(
$this->getReference(
LoadScopes::$references[array_rand(LoadScopes::$references)]
)
);
$manager->persist($event);
$events[] = $event;
}
return $events;
}
public function getOrder()
{
return 30010;
@@ -37,62 +63,36 @@ class LoadParticipation extends AbstractFixture implements OrderedFixtureInterfa
public function load(ObjectManager $manager)
{
$centers = $manager->getRepository('ChillMainBundle:Center')
->findAll();
foreach($centers as $center) {
->findAll();
foreach ($centers as $center) {
$people = $manager->getRepository('ChillPersonBundle:Person')
->findBy(array('center' => $center));
->findBy(['center' => $center]);
$events = $this->createEvents($center, $manager);
/* @var $person \Chill\PersonBundle\Entity\Person */
foreach ($people as $person) {
$nb = rand(0,3);
for ($i=0; $i<$nb; $i++) {
$nb = rand(0, 3);
for ($i = 0; $i < $nb; ++$i) {
$event = $events[array_rand($events)];
$role = $event->getType()->getRoles()->get(
array_rand($event->getType()->getRoles()->toArray()));
array_rand($event->getType()->getRoles()->toArray())
);
$status = $event->getType()->getStatuses()->get(
array_rand($event->getType()->getStatuses()->toArray()));
array_rand($event->getType()->getStatuses()->toArray())
);
$participation = (new Participation())
->setPerson($person)
->setRole($role)
->setStatus($status)
->setEvent($event)
;
->setPerson($person)
->setRole($role)
->setStatus($status)
->setEvent($event);
$manager->persist($participation);
}
}
}
$manager->flush();
}
public function createEvents(Center $center, ObjectManager $manager)
{
$expectedNumber = 20;
$events = array();
for($i=0; $i<$expectedNumber; $i++) {
$event = (new Event())
->setDate($this->faker->dateTimeBetween('-2 years', '+6 months'))
->setName($this->faker->words(rand(2,4), true))
->setType($this->getReference(LoadEventTypes::$refs[array_rand(LoadEventTypes::$refs)]))
->setCenter($center)
->setCircle(
$this->getReference(
LoadScopes::$references[array_rand(LoadScopes::$references)]
)
)
;
$manager->persist($event);
$events[] = $event;
}
return $events;
}
}

View File

@@ -1,45 +1,37 @@
<?php
/*
* Copyright (C) 2016 Julien Fastré <julien.fastre@champs-libres.coop>
/**
* Chill is a software for social workers
*
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\DataFixtures\ORM;
use Chill\MainBundle\DataFixtures\ORM\LoadPermissionsGroup;
use Chill\MainBundle\DataFixtures\ORM\LoadScopes;
use Chill\MainBundle\Entity\RoleScope;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Chill\MainBundle\DataFixtures\ORM\LoadPermissionsGroup;
use Chill\MainBundle\Entity\RoleScope;
use Chill\MainBundle\DataFixtures\ORM\LoadScopes;
use Doctrine\Persistence\ObjectManager;
/**
* Add roles to existing groups
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
* Add roles to existing groups.
*/
class LoadRolesACL extends AbstractFixture implements OrderedFixtureInterface
{
public function getOrder()
{
return 30011;
}
public function load(ObjectManager $manager)
{
foreach (LoadPermissionsGroup::$refs as $permissionsGroupRef) {
$permissionsGroup = $this->getReference($permissionsGroupRef);
foreach (LoadScopes::$references as $scopeRef){
foreach (LoadScopes::$references as $scopeRef) {
$scope = $this->getReference($scopeRef);
//create permission group
switch ($permissionsGroup->getName()) {
@@ -47,37 +39,43 @@ class LoadRolesACL extends AbstractFixture implements OrderedFixtureInterface
if ($scope->getName()['en'] === 'administrative') {
break 2; // we do not want any power on administrative
}
break;
case 'administrative':
case 'direction':
if (in_array($scope->getName()['en'], array('administrative', 'social'), true)) {
if (in_array($scope->getName()['en'], ['administrative', 'social'], true)) {
break 2; // we do not want any power on social or administrative
}
break;
}
printf("Adding CHILL_EVENT_UPDATE & CHILL_EVENT_CREATE "
. "& CHILL_EVENT_PARTICIPATION_UPDATE & CHILL_EVENT_PARTICIPATION_CREATE "
. "& CHILL_EVENT_SEE & CHILL_EVENT_SEE_DETAILS "
. "to %s "
printf(
'Adding CHILL_EVENT_UPDATE & CHILL_EVENT_CREATE '
. '& CHILL_EVENT_PARTICIPATION_UPDATE & CHILL_EVENT_PARTICIPATION_CREATE '
. '& CHILL_EVENT_SEE & CHILL_EVENT_SEE_DETAILS '
. 'to %s '
. "permission group, scope '%s' \n",
$permissionsGroup->getName(), $scope->getName()['en']);
$permissionsGroup->getName(),
$scope->getName()['en']
);
$roleScopeUpdate = (new RoleScope())
->setRole('CHILL_EVENT_UPDATE')
->setScope($scope);
->setRole('CHILL_EVENT_UPDATE')
->setScope($scope);
$roleScopeUpdate2 = (new RoleScope())
->setRole('CHILL_EVENT_PARTICIPATION_UPDATE')
->setScope($scope);
->setRole('CHILL_EVENT_PARTICIPATION_UPDATE')
->setScope($scope);
$permissionsGroup->addRoleScope($roleScopeUpdate);
$permissionsGroup->addRoleScope($roleScopeUpdate2);
$roleScopeCreate = (new RoleScope())
->setRole('CHILL_EVENT_CREATE')
->setScope($scope);
->setRole('CHILL_EVENT_CREATE')
->setScope($scope);
$roleScopeCreate2 = (new RoleScope())
->setRole('CHILL_EVENT_PARTICIPATION_CREATE')
->setScope($scope);
->setRole('CHILL_EVENT_PARTICIPATION_CREATE')
->setScope($scope);
$permissionsGroup->addRoleScope($roleScopeCreate);
$permissionsGroup->addRoleScope($roleScopeCreate2);
@@ -97,15 +95,8 @@ class LoadRolesACL extends AbstractFixture implements OrderedFixtureInterface
$manager->persist($roleScopeSee);
$manager->persist($roleScopeSee2);
}
}
$manager->flush();
}
public function getOrder()
{
return 30011;
}
}

View File

@@ -1,30 +1,34 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Chill\EventBundle\Security\Authorization\EventVoter;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
* This is the class that loads and manages your bundle configuration.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class ChillEventExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../config'));
$loader->load('services.yaml');
$loader->load('services/authorization.yaml');
$loader->load('services/controller.yaml');
@@ -35,46 +39,42 @@ class ChillEventExtension extends Extension implements PrependExtensionInterface
$loader->load('services/search.yaml');
$loader->load('services/timeline.yaml');
}
/* (non-PHPdoc)
* @see \Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface::prepend()
*/
public function prepend(ContainerBuilder $container)
/* (non-PHPdoc)
* @see \Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface::prepend()
*/
public function prepend(ContainerBuilder $container)
{
$this->prependAuthorization($container);
$this->prependRoute($container);
}
/**
* add route to route loader for chill
*
* @param ContainerBuilder $container
* add authorization hierarchy.
*/
protected function prependAuthorization(ContainerBuilder $container)
{
$container->prependExtensionConfig('security', [
'role_hierarchy' => [
EventVoter::SEE_DETAILS => [EventVoter::SEE],
EventVoter::UPDATE => [EventVoter::SEE_DETAILS],
EventVoter::CREATE => [EventVoter::SEE_DETAILS],
],
]);
}
/**
* add route to route loader for chill.
*/
protected function prependRoute(ContainerBuilder $container)
{
//add routes for custom bundle
$container->prependExtensionConfig('chill_main', array(
'routing' => array(
'resources' => array(
'@ChillEventBundle/config/routes.yaml'
)
)
));
}
/**
* add authorization hierarchy
*
* @param ContainerBuilder $container
*/
protected function prependAuthorization(ContainerBuilder $container)
{
$container->prependExtensionConfig('security', array(
'role_hierarchy' => array(
EventVoter::SEE_DETAILS => array(EventVoter::SEE),
EventVoter::UPDATE => array(EventVoter::SEE_DETAILS),
EventVoter::CREATE => array(EventVoter::SEE_DETAILS)
)
));
$container->prependExtensionConfig('chill_main', [
'routing' => [
'resources' => [
'@ChillEventBundle/config/routes.yaml',
],
],
]);
}
}

View File

@@ -1,20 +1,24 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('chill_event');

View File

@@ -1,47 +1,55 @@
<?php
/*
/**
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Chill\MainBundle\Entity\User;
use ArrayIterator;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Scope;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Chill\MainBundle\Entity\HasCenterInterface;
use Chill\MainBundle\Entity\HasScopeInterface;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Traversable;
/**
* Class Event
* Class Event.
*
* @package Chill\EventBundle\Entity
* @ORM\Entity(repositoryClass="Chill\EventBundle\Repository\EventRepository")
* @ORM\Table(name="chill_event_event")
* @ORM\HasLifecycleCallbacks()
* @ORM\HasLifecycleCallbacks
*/
class Event implements HasCenterInterface, HasScopeInterface
{
/**
* @var integer
* @var Center
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Center")
*/
private $center;
/**
* @var Scope
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Scope")
*/
private $circle;
/**
* @var DateTime
* @ORM\Column(type="datetime")
*/
private $date;
/**
* @var int
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
@@ -49,6 +57,12 @@ class Event implements HasCenterInterface, HasScopeInterface
*/
private $id;
/**
* @var User
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\User")
*/
private $moderator;
/**
* @var string
* @ORM\Column(type="string", length=150)
@@ -56,48 +70,19 @@ class Event implements HasCenterInterface, HasScopeInterface
private $name;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
* @var Participation
* @ORM\OneToMany(
* targetEntity="Chill\EventBundle\Entity\Participation",
* mappedBy="event")
*/
private $date;
private $participations;
/**
*
* @var Center
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Center")
*/
private $center;
/**
*
* @var EventType
* @ORM\ManyToOne(targetEntity="Chill\EventBundle\Entity\EventType")
*/
private $type;
/**
*
* @var Scope
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Scope")
*/
private $circle;
/**
* @var Participation
* @ORM\OneToMany(
* targetEntity="Chill\EventBundle\Entity\Participation",
* mappedBy="event")
*/
private $participations;
/**
*
* @var User
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\User")
*/
private $moderator;
/**
* Event constructor.
*/
@@ -107,130 +92,8 @@ class Event implements HasCenterInterface, HasScopeInterface
}
/**
* Get id
* Add participation.
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set label
*
* @param string $label
* @return Event
*/
public function setName($label)
{
$this->name = $label;
return $this;
}
/**
* Get label
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set date
*
* @param \DateTime $date
* @return Event
*/
public function setDate(\DateTime $date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* @return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* @param Center $center
* @return $this
*/
public function setCenter(Center $center)
{
$this->center = $center;
return $this;
}
/**
* @return EventType
*/
public function getType()
{
return $this->type;
}
/**
* @param EventType $type
* @return $this
*/
public function setType(EventType $type)
{
$this->type = $type;
return $this;
}
/**
* @return Center
*/
public function getCenter()
{
return $this->center;
}
/**
* @return Scope
*/
public function getCircle()
{
return $this->circle;
}
/**
* @param Scope $circle
* @return $this
*/
public function setCircle(\Chill\MainBundle\Entity\Scope $circle)
{
$this->circle = $circle;
return $this;
}
/**
* @deprecated
* @return Scope
*/
public function getScope()
{
return $this->getCircle();
}
/**
* Add participation
*
* @param Participation $participation
* @return Event
*/
public function addParticipation(Participation $participation)
@@ -241,40 +104,41 @@ class Event implements HasCenterInterface, HasScopeInterface
}
/**
* Remove participation
*
* @param Participation $participation
* @return Center
*/
public function removeParticipation(Participation $participation)
public function getCenter()
{
$this->participations->removeElement($participation);
return $this->center;
}
/**
* @return \ArrayIterator|\Traversable|Collection
* @return Scope
*/
public function getParticipations()
public function getCircle()
{
return $this->getParticipationsOrdered();
return $this->circle;
}
/**
* Sort Collection of Participations
* Get date.
*
* @return \ArrayIterator|\Traversable
* @return DateTime
*/
public function getParticipationsOrdered() {
$iterator = $this->participations->getIterator();
$iterator->uasort(function($first, $second)
{
return strnatcasecmp($first->getPerson()->getFirstName(), $second->getPerson()->getFirstName());
});
return $iterator;
public function getDate()
{
return $this->date;
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return int
*/
@@ -282,14 +146,132 @@ class Event implements HasCenterInterface, HasScopeInterface
{
return $this->moderator;
}
/**
* Get label.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return ArrayIterator|Collection|Traversable
*/
public function getParticipations()
{
return $this->getParticipationsOrdered();
}
/**
* Sort Collection of Participations.
*
* @return ArrayIterator|Traversable
*/
public function getParticipationsOrdered()
{
$iterator = $this->participations->getIterator();
$iterator->uasort(function ($first, $second) {
return strnatcasecmp($first->getPerson()->getFirstName(), $second->getPerson()->getFirstName());
});
return $iterator;
}
/**
* @deprecated
*
* @return Scope
*/
public function getScope()
{
return $this->getCircle();
}
/**
* @return EventType
*/
public function getType()
{
return $this->type;
}
/**
* Remove participation.
*/
public function removeParticipation(Participation $participation)
{
$this->participations->removeElement($participation);
}
/**
* @return $this
*/
public function setCenter(Center $center)
{
$this->center = $center;
return $this;
}
/**
* @return $this
*/
public function setCircle(Scope $circle)
{
$this->circle = $circle;
return $this;
}
/**
* Set date.
*
* @return Event
*/
public function setDate(DateTime $date)
{
$this->date = $date;
return $this;
}
/**
* @param int $moderator
*
* @return Event
*/
public function setModerator($moderator)
{
$this->moderator = $moderator;
return $this;
}
/**
* Set label.
*
* @param string $label
*
* @return Event
*/
public function setName($label)
{
$this->name = $label;
return $this;
}
/**
* @return $this
*/
public function setType(EventType $type)
{
$this->type = $type;
return $this;
}
}

View File

@@ -1,42 +1,35 @@
<?php
/*
/**
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Class EventType
* Class EventType.
*
* @package Chill\EventBundle\Entity
* @ORM\Entity()
* @ORM\Entity
* @ORM\Table(name="chill_event_event_type")
* @ORM\HasLifecycleCallbacks()
* @ORM\HasLifecycleCallbacks
*/
class EventType
{
/**
* @var integer
* @var bool
* @ORM\Column(type="boolean")
*/
private $active;
/**
* @var int
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
@@ -50,17 +43,11 @@ class EventType
*/
private $name;
/**
* @var boolean
* @ORM\Column(type="boolean")
*/
private $active;
/**
* @var Collection
* @ORM\OneToMany(
* targetEntity="Chill\EventBundle\Entity\Role",
* mappedBy="type")
* mappedBy="type")
*/
private $roles;
@@ -68,12 +55,12 @@ class EventType
* @var Collection
* @ORM\OneToMany(
* targetEntity="Chill\EventBundle\Entity\Status",
* mappedBy="type")
* mappedBy="type")
*/
private $statuses;
/**
* Constructor
* Constructor.
*/
public function __construct()
{
@@ -82,65 +69,8 @@ class EventType
}
/**
* Get id
* Add role.
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set label
*
* @param array $label
* @return EventType
*/
public function setName($label)
{
$this->name = $label;
return $this;
}
/**
* Get label
*
* @return array
*/
public function getName()
{
return $this->name;
}
/**
* Set active
*
* @param boolean $active
* @return EventType
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* @return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Add role
*
* @param Role $role
* @return EventType
*/
public function addRole(Role $role)
@@ -151,24 +81,8 @@ class EventType
}
/**
* Remove role
* Add status.
*
* @param Role $role
*/
public function removeRole(Role $role)
{
$this->roles->removeElement($role);
}
public function getRoles()
{
return $this->roles;
}
/**
* Add status
*
* @param Status $status
* @return EventType
*/
public function addStatus(Status $status)
@@ -179,17 +93,42 @@ class EventType
}
/**
* Remove status
* Get active.
*
* @param Status $status
* @return bool
*/
public function removeStatus(Status $status)
public function getActive()
{
$this->statuses->removeElement($status);
return $this->active;
}
/**
* Get statuses
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Get label.
*
* @return array
*/
public function getName()
{
return $this->name;
}
public function getRoles()
{
return $this->roles;
}
/**
* Get statuses.
*
* @return Collection
*/
@@ -197,4 +136,48 @@ class EventType
{
return $this->statuses;
}
/**
* Remove role.
*/
public function removeRole(Role $role)
{
$this->roles->removeElement($role);
}
/**
* Remove status.
*/
public function removeStatus(Status $status)
{
$this->statuses->removeElement($status);
}
/**
* Set active.
*
* @param bool $active
*
* @return EventType
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* Set label.
*
* @param array $label
*
* @return EventType
*/
public function setName($label)
{
$this->name = $label;
return $this;
}
}

View File

@@ -1,47 +1,45 @@
<?php
/*
/**
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use ArrayAccess;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\HasCenterInterface;
use Chill\MainBundle\Entity\HasScopeInterface;
use Chill\MainBundle\Entity\Scope;
use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\HasScopeInterface;
use Chill\MainBundle\Entity\HasCenterInterface;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
use RuntimeException;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Class Participation
* Class Participation.
*
* @package Chill\EventBundle\Entity
* @ORM\Entity(
* repositoryClass="Chill\EventBundle\Repository\ParticipationRepository")
* repositoryClass="Chill\EventBundle\Repository\ParticipationRepository")
* @ORM\Table(name="chill_event_participation")
* @ORM\HasLifecycleCallbacks()
* @ORM\HasLifecycleCallbacks
*/
class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAccess
class Participation implements HasCenterInterface, HasScopeInterface, ArrayAccess
{
/**
* @var integer
* @var Event
* @ORM\ManyToOne(
* targetEntity="Chill\EventBundle\Entity\Event",
* inversedBy="participations")
*/
private $event;
/**
* @var int
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
@@ -50,18 +48,10 @@ class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAcce
private $id;
/**
* @var \DateTime
* @var DateTime
* @ORM\Column(type="datetime")
*/
private $lastUpdate;
/**
* @var Event
* @ORM\ManyToOne(
* targetEntity="Chill\EventBundle\Entity\Event",
* inversedBy="participations")
*/
private $event;
/**
* @var Person
@@ -81,60 +71,21 @@ class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAcce
*/
private $status;
/**
* Get id
*
* @return integer
* @return Center
*/
public function getId()
public function getCenter()
{
return $this->id;
}
/**
* Set lastUpdate
*
* @param \DateTime $lastUpdate
* @return Participation
*/
protected function update()
{
$this->lastUpdate = new \DateTime('now');
return $this;
}
/**
* Get lastUpdate
*
* @return \DateTime
*/
public function getLastUpdate()
{
return $this->lastUpdate;
}
/**
* Set event
*
* @param Event $event
* @return Participation
*/
public function setEvent(Event $event = null)
{
if ($this->event !== $event) {
$this->update();
if ($this->getEvent() === null) {
throw new RuntimeException('The event is not linked with this instance. '
. 'You should initialize the event with a valid center before.');
}
$this->event = $event;
return $this;
return $this->getEvent()->getCenter();
}
/**
* Get event
* Get event.
*
* @return Event
*/
@@ -144,24 +95,27 @@ class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAcce
}
/**
* Set person
* Get id.
*
* @param Person $person
* @return Participation
* @return int
*/
public function setPerson(Person $person = null)
public function getId()
{
if ($person !== $this->person) {
$this->update();
}
$this->person = $person;
return $this;
return $this->id;
}
/**
* Get person
* Get lastUpdate.
*
* @return DateTime
*/
public function getLastUpdate()
{
return $this->lastUpdate;
}
/**
* Get person.
*
* @return Person
*/
@@ -171,12 +125,190 @@ class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAcce
}
/**
* Set role
* Get role.
*
* @return Role
*/
public function getRole()
{
return $this->role;
}
/**
* @return Scope
*/
public function getScope()
{
if ($this->getEvent() === null) {
throw new RuntimeException('The event is not linked with this instance. '
. 'You should initialize the event with a valid center before.');
}
return $this->getEvent()->getCircle();
}
/**
* Get status.
*
* @return Status
*/
public function getStatus()
{
return $this->status;
}
/**
* Check that :.
*
* - the role can be associated with this event type
* - the status can be associated with this event type
*/
public function isConsistent(ExecutionContextInterface $context)
{
if ($this->getEvent() === null || $this->getRole() === null || $this->getStatus() === null) {
return;
}
if ($this->getRole()->getType()->getId() !==
$this->getEvent()->getType()->getId()) {
$context->buildViolation('The role is not allowed with this event type')
->atPath('role')
->addViolation();
}
if ($this->getStatus()->getType()->getId() !==
$this->getEvent()->getType()->getId()) {
$context->buildViolation('The status is not allowed with this event type')
->atPath('status')
->addViolation();
}
}
/**
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset)
{
return in_array($offset, [
'person', 'role', 'status', 'event',
]);
}
/**
* @param mixed $offset
*
* @return Event|mixed|Person|Role|Status
*/
public function offsetGet($offset)
{
switch ($offset) {
case 'person':
return $this->getPerson();
break;
case 'role':
return $this->getRole();
break;
case 'status':
return $this->getStatus();
break;
case 'event':
return $this->getEvent();
break;
}
}
/**
* @param mixed $offset
* @param mixed $value
*
* @return Participation|void
*/
public function offsetSet($offset, $value)
{
switch ($offset) {
case 'person':
return $this->setPerson($value);
break;
case 'role':
return $this->setRole($value);
break;
case 'status':
return $this->setStatus($value);
break;
case 'event':
return $this->setEvent($value);
break;
}
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset)
{
$this->offsetSet($offset, null);
}
/**
* Set event.
*
* @param Event $event
*
* @param Role $role
* @return Participation
*/
public function setRole(Role $role = null)
public function setEvent(?Event $event = null)
{
if ($this->event !== $event) {
$this->update();
}
$this->event = $event;
return $this;
}
/**
* Set person.
*
* @param Person $person
*
* @return Participation
*/
public function setPerson(?Person $person = null)
{
if ($person !== $this->person) {
$this->update();
}
$this->person = $person;
return $this;
}
/**
* Set role.
*
* @param Role $role
*
* @return Participation
*/
public function setRole(?Role $role = null)
{
if ($role !== $this->role) {
$this->update();
@@ -187,160 +319,32 @@ class Participation implements HasCenterInterface, HasScopeInterface, \ArrayAcce
}
/**
* Get role
*
* @return Role
*/
public function getRole()
{
return $this->role;
}
/**
* Set status
* Set status.
*
* @param Status $status
*
* @return Participation
*/
public function setStatus(Status $status = null)
public function setStatus(?Status $status = null)
{
if ($this->status !== $status) {
$this->update();
}
$this->status = $status;
return $this;
}
/**
* Get status
* Set lastUpdate.
*
* @return Status
* @return Participation
*/
public function getStatus()
protected function update()
{
return $this->status;
}
/**
* @return Center
*/
public function getCenter()
{
if ($this->getEvent() === NULL) {
throw new \RuntimeException('The event is not linked with this instance. '
. 'You should initialize the event with a valid center before.');
}
return $this->getEvent()->getCenter();
}
/**
* @return Scope
*/
public function getScope()
{
if ($this->getEvent() === NULL) {
throw new \RuntimeException('The event is not linked with this instance. '
. 'You should initialize the event with a valid center before.');
}
return $this->getEvent()->getCircle();
}
/**
* Check that :
*
* - the role can be associated with this event type
* - the status can be associated with this event type
*
* @param ExecutionContextInterface $context
*/
public function isConsistent(ExecutionContextInterface $context)
{
if ($this->getEvent() === NULL || $this->getRole() === NULL || $this->getStatus() === NULL) {
return;
}
if ($this->getRole()->getType()->getId() !==
$this->getEvent()->getType()->getId()) {
$context->buildViolation('The role is not allowed with this event type')
->atPath('role')
->addViolation();
}
if ($this->getStatus()->getType()->getId() !==
$this->getEvent()->getType()->getId()) {
$context->buildViolation('The status is not allowed with this event type')
->atPath('status')
->addViolation();
}
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return in_array($offset, array(
'person', 'role', 'status', 'event'
));
}
/**
* @param mixed $offset
* @return Event|Role|Status|Person|mixed
*/
public function offsetGet($offset)
{
switch ($offset) {
case 'person':
return $this->getPerson();
break;
case 'role':
return $this->getRole();
break;
case 'status':
return $this->getStatus();
break;
case 'event':
return $this->getEvent();
break;
}
}
/**
* @param mixed $offset
* @param mixed $value
* @return Participation|void
*/
public function offsetSet($offset, $value)
{
switch($offset) {
case 'person':
return $this->setPerson($value);
break;
case 'role':
return $this->setRole($value);
break;
case 'status':
return $this->setStatus($value);
break;
case 'event':
return $this->setEvent($value);
break;
}
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset)
{
$this->offsetSet($offset, null);
}
$this->lastUpdate = new DateTime('now');
return $this;
}
}

View File

@@ -1,22 +1,10 @@
<?php
/*
/**
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Entity;
@@ -24,17 +12,22 @@ namespace Chill\EventBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Role
* Class Role.
*
* @package Chill\EventBundle\Entity
* @ORM\Entity()
* @ORM\Entity
* @ORM\Table(name="chill_event_role")
* @ORM\HasLifecycleCallbacks()
* @ORM\HasLifecycleCallbacks
*/
class Role
{
/**
* @var integer
* @var bool
* @ORM\Column(type="boolean")
*/
private $active;
/**
* @var int
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
@@ -48,25 +41,28 @@ class Role
*/
private $name;
/**
* @var boolean
* @ORM\Column(type="boolean")
*/
private $active;
/**
* @var EventType
* @ORM\ManyToOne(
* targetEntity="Chill\EventBundle\Entity\EventType",
* inversedBy="roles")
* inversedBy="roles")
*/
private $type;
/**
* Get active.
*
* @return bool
*/
public function getActive()
{
return $this->active;
}
/**
* Get id
* Get id.
*
* @return integer
* @return int
*/
public function getId()
{
@@ -74,20 +70,7 @@ class Role
}
/**
* Set label
*
* @param array $label
* @return Role
*/
public function setName($label)
{
$this->name = $label;
return $this;
}
/**
* Get label
* Get label.
*
* @return array
*/
@@ -97,9 +80,20 @@ class Role
}
/**
* Set active
* Get type.
*
* @return EventType
*/
public function getType()
{
return $this->type;
}
/**
* Set active.
*
* @param bool $active
*
* @param boolean $active
* @return Role
*/
public function setActive($active)
@@ -110,36 +104,30 @@ class Role
}
/**
* Get active
* Set label.
*
* @return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Set type
* @param array $label
*
* @param EventType $type
* @return Role
*/
public function setType(EventType $type = null)
public function setName($label)
{
$this->type = $type;
$this->name = $label;
return $this;
}
/**
* Get type
* Set type.
*
* @return EventType
* @param EventType $type
*
* @return Role
*/
public function getType()
public function setType(?EventType $type = null)
{
return $this->type;
$this->type = $type;
return $this;
}
}

View File

@@ -1,22 +1,10 @@
<?php
/*
/**
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Entity;
@@ -24,17 +12,22 @@ namespace Chill\EventBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Status
* Class Status.
*
* @package Chill\EventBundle\Entity
* @ORM\Entity()
* @ORM\Entity
* @ORM\Table(name="chill_event_status")
* @ORM\HasLifecycleCallbacks()
* @ORM\HasLifecycleCallbacks
*/
class Status
{
/**
* @var integer
* @var bool
* @ORM\Column(type="boolean")
*/
private $active;
/**
* @var int
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
@@ -48,25 +41,28 @@ class Status
*/
private $name;
/**
* @var boolean
* @ORM\Column(type="boolean")
*/
private $active;
/**
* @var EventType
* @ORM\ManyToOne(
* targetEntity="Chill\EventBundle\Entity\EventType",
* inversedBy="statuses")
* inversedBy="statuses")
*/
private $type;
/**
* Get active.
*
* @return bool
*/
public function getActive()
{
return $this->active;
}
/**
* Get id
* Get id.
*
* @return integer
* @return int
*/
public function getId()
{
@@ -74,20 +70,7 @@ class Status
}
/**
* Set label
*
* @param array $name
* @return Status
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get label
* Get label.
*
* @return array
*/
@@ -96,11 +79,21 @@ class Status
return $this->name;
}
/**
* Get type.
*
* @return EventType
*/
public function getType()
{
return $this->type;
}
/**
* Set active
* Set active.
*
* @param bool $active
*
* @param boolean $active
* @return Status
*/
public function setActive($active)
@@ -111,36 +104,30 @@ class Status
}
/**
* Get active
* Set label.
*
* @return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Set type
* @param array $name
*
* @param EventType $type
* @return Status
*/
public function setType(EventType $type = null)
public function setName($name)
{
$this->type = $type;
$this->name = $name;
return $this;
}
/**
* Get type
* Set type.
*
* @return EventType
* @param EventType $type
*
* @return Status
*/
public function getType()
public function setType(?EventType $type = null)
{
return $this->type;
$this->type = $type;
return $this;
}
}

View File

@@ -1,29 +1,23 @@
<?php
/*
* Copyright (C) 2018 Champs-Libres <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form\ChoiceLoader;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Doctrine\ORM\EntityRepository;
use Chill\EventBundle\Entity\Event;
use Doctrine\ORM\EntityRepository;
use RuntimeException;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
use function call_user_func;
use function in_array;
/***
/*
* Class EventChoiceLoader
*
* @package Chill\EventBundle\Form\ChoiceLoader
@@ -31,38 +25,99 @@ use Chill\EventBundle\Entity\Event;
*/
class EventChoiceLoader implements ChoiceLoaderInterface
{
/**
* @var EntityRepository
*/
protected $eventRepository;
/**
* @var array
*/
protected $lazyLoadedEvents = [];
/**
* @var array
*/
protected $centers = [];
/**
* @var EntityRepository
*/
protected $eventRepository;
/**
* @var array
*/
protected $lazyLoadedEvents = [];
/**
* EventChoiceLoader constructor.
*
* @param EntityRepository $eventRepository
* @param array|null $centers
*/
public function __construct(
EntityRepository $eventRepository,
array $centers = null
?array $centers = null
) {
$this->eventRepository = $eventRepository;
if (NULL !== $centers) {
if (null !== $centers) {
$this->centers = $centers;
}
}
/**
* @param null $value
*/
public function loadChoiceList($value = null): ChoiceListInterface
{
return new \Symfony\Component\Form\ChoiceList\ArrayChoiceList(
$this->lazyLoadedEvents,
function (Event $p) use ($value) {
return call_user_func($value, $p);
}
);
}
/**
* @param null $value
*
* @return array
*/
public function loadChoicesForValues(array $values, $value = null)
{
$choices = [];
foreach ($values as $value) {
if (empty($value)) {
continue;
}
$event = $this->eventRepository->find($value);
if ($this->hasCenterFilter()
&& !in_array($event->getCenter(), $this->centers)) {
throw new RuntimeException('chosen an event not in correct center');
}
$choices[] = $event;
}
return $choices;
}
/**
* @param null $value
*
* @return array|string[]
*/
public function loadValuesForChoices(array $choices, $value = null)
{
$values = [];
foreach ($choices as $choice) {
if (null === $choice) {
$values[] = null;
continue;
}
$id = call_user_func($value, $choice);
$values[] = $id;
$this->lazyLoadedEvents[$id] = $choice;
}
return $values;
}
/**
* @return bool
*/
@@ -70,69 +125,4 @@ class EventChoiceLoader implements ChoiceLoaderInterface
{
return count($this->centers) > 0;
}
/**
* @param null $value
* @return ChoiceListInterface
*/
public function loadChoiceList($value = null): ChoiceListInterface
{
$list = new \Symfony\Component\Form\ChoiceList\ArrayChoiceList(
$this->lazyLoadedEvents,
function(Event $p) use ($value) {
return \call_user_func($value, $p);
});
return $list;
}
/**
* @param array $values
* @param null $value
* @return array
*/
public function loadChoicesForValues(array $values, $value = null)
{
$choices = [];
foreach($values as $value) {
if (empty($value)) {
continue;
}
$event = $this->eventRepository->find($value);
if ($this->hasCenterFilter() &&
!\in_array($event->getCenter(), $this->centers)) {
throw new \RuntimeException("chosen an event not in correct center");
}
$choices[] = $event;
}
return $choices;
}
/**
* @param array $choices
* @param null $value
* @return array|string[]
*/
public function loadValuesForChoices(array $choices, $value = null)
{
$values = [];
foreach ($choices as $choice) {
if (NULL === $choice) {
$values[] = null;
continue;
}
$id = \call_user_func($value, $choice);
$values[] = $id;
$this->lazyLoadedEvents[$id] = $choice;
}
return $values;
}
}

View File

@@ -1,91 +1,63 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form;
use Chill\EventBundle\Form\Type\PickEventTypeType;
use Chill\MainBundle\Form\Type\ScopePickerType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Form\Type\ChillDateTimeType;
use Chill\MainBundle\Form\Type\ScopePickerType;
use Chill\MainBundle\Form\Type\UserPickerType;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role;
class EventType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('date', ChillDateTimeType::class, array(
'required' => true
))
->add('circle', ScopePickerType::class, [
'center' => $options['center'],
'role' => $options['role']
->add('date', ChillDateTimeType::class, [
'required' => true,
])
->add('type', PickEventTypeType::class, array(
'placeholder' => 'Pick a type of event',
'attr' => array(
'class' => ''
)
))
->add('moderator', UserPickerType::class, array(
->add('circle', ScopePickerType::class, [
'center' => $options['center'],
'role' => $options['role'],
'role' => $options['role'],
])
->add('type', PickEventTypeType::class, [
'placeholder' => 'Pick a type of event',
'attr' => [
'class' => '',
],
])
->add('moderator', UserPickerType::class, [
'center' => $options['center'],
'role' => $options['role'],
'placeholder' => 'Pick a moderator',
'attr' => array(
'class' => ''
),
'required' => false
))
;
'attr' => [
'class' => '',
],
'required' => false,
]);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Chill\EventBundle\Entity\Event'
));
$resolver->setDefaults([
'data_class' => 'Chill\EventBundle\Entity\Event',
]);
$resolver
->setRequired(array('center', 'role'))
->setRequired(['center', 'role'])
->setAllowedTypes('center', Center::class)
->setAllowedTypes('role', Role::class)
;
->setAllowedTypes('role', Role::class);
}
/**

View File

@@ -1,34 +1,26 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form;
use Chill\MainBundle\Form\Type\TranslatableStringFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Chill\MainBundle\Form\Type\TranslatableStringFormType;
class EventTypeType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TranslatableStringFormType::class)
->add('active')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Chill\EventBundle\Entity\EventType'
));
->add('active');
}
/**
@@ -38,4 +30,11 @@ class EventTypeType extends AbstractType
{
return 'chill_eventbundle_eventtype';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'data_class' => 'Chill\EventBundle\Entity\EventType',
]);
}
}

View File

@@ -1,76 +1,60 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form;
use Chill\EventBundle\Entity\EventType;
use Chill\EventBundle\Entity\Status;
use Chill\EventBundle\Form\Type\PickRoleType;
use Chill\EventBundle\Form\Type\PickStatusType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Chill\EventBundle\Entity\EventType;
use Chill\EventBundle\Entity\Status;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\EventBundle\Form\Type\PickRoleType;
use Chill\EventBundle\Form\Type\PickStatusType;
/**
* A type to create a participation
*
* If the `event` option is defined, the role will be restricted
* A type to create a participation.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* If the `event` option is defined, the role will be restricted
*/
class ParticipationType extends AbstractType
{
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
public function __construct(TranslatableStringHelper $translatableStringHelper)
{
$this->translatableStringHelper = $translatableStringHelper;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// local copy of variable for Closure
$translatableStringHelper = $this->translatableStringHelper;
// add role
$builder->add('role', PickRoleType::class, array(
'event_type' => $options['event_type']
));
$builder->add('role', PickRoleType::class, [
'event_type' => $options['event_type'],
]);
// add a status
$builder->add('status', PickStatusType::class, array(
'event_type' => $options['event_type']
));
$builder->add('status', PickStatusType::class, [
'event_type' => $options['event_type'],
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefined('event_type')
->setAllowedTypes('event_type', array('null', EventType::class))
->setDefault('event_type', 'null');
->setAllowedTypes('event_type', ['null', EventType::class])
->setDefault('event_type', 'null');
}
}

View File

@@ -1,53 +1,45 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Chill\EventBundle\Entity\EventType;
use Chill\MainBundle\Form\Type\TranslatableStringFormType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Chill\EventBundle\Entity\EventType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RoleType extends AbstractType
{
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
public function __construct(TranslatableStringHelper $translatableStringHelper) {
public function __construct(TranslatableStringHelper $translatableStringHelper)
{
$this->translatableStringHelper = $translatableStringHelper;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TranslatableStringFormType::class)
->add('active')
->add('type', EntityType::class, array(
->add('type', EntityType::class, [
'class' => EventType::class,
'choice_label' => function (EventType $e) {
'choice_label' => function (EventType $e) {
return $this->translatableStringHelper->localize($e->getName());
}
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Chill\EventBundle\Entity\Role'
));
},
]);
}
/**
@@ -57,4 +49,11 @@ class RoleType extends AbstractType
{
return 'chill_eventbundle_role';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'data_class' => 'Chill\EventBundle\Entity\Role',
]);
}
}

View File

@@ -1,36 +1,28 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form;
use Chill\EventBundle\Form\Type\PickEventTypeType;
use Chill\MainBundle\Form\Type\TranslatableStringFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Chill\MainBundle\Form\Type\TranslatableStringFormType;
use Chill\EventBundle\Form\Type\PickEventTypeType;
class StatusType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TranslatableStringFormType::class)
->add('active')
->add('type', PickEventTypeType::class)
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Chill\EventBundle\Entity\Status'
));
->add('type', PickEventTypeType::class);
}
/**
@@ -40,4 +32,11 @@ class StatusType extends AbstractType
{
return 'chill_eventbundle_status';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'data_class' => 'Chill\EventBundle\Entity\Status',
]);
}
}

View File

@@ -1,23 +1,10 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2014-2019, 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form\Type;
@@ -30,6 +17,7 @@ use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use RuntimeException;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\Form\AbstractType;
@@ -41,47 +29,37 @@ use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Class PickEventType
*
* @package Chill\EventBundle\Form\Type
* @author Mathieu Jaumotte jaum_mathieu@collectifs.net
* Class PickEventType.
*/
class PickEventType extends AbstractType
{
/**
* @var EventRepository
*/
protected $eventRepository;
/**
* @var User
*/
protected $user;
/**
* @var AuthorizationHelper
*/
protected $authorizationHelper;
/**
* @var UrlGeneratorInterface
* @var EventRepository
*/
protected $urlGenerator;
protected $eventRepository;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @var UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* @var User
*/
protected $user;
/**
* PickEventType constructor.
*
* @param EventRepository $eventRepository
* @param TokenStorageInterface $tokenStorage
* @param AuthorizationHelper $authorizationHelper
* @param UrlGeneratorInterface $urlGenerator
* @param TranslatorInterface $translator
*/
public function __construct(
EventRepository $eventRepository,
@@ -96,80 +74,69 @@ class PickEventType extends AbstractType
$this->urlGenerator = $urlGenerator;
$this->translator = $translator;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
// add the possibles options for this type
$resolver
->setDefined('centers')
->addAllowedTypes('centers', array('array', Center::class, 'null'))
->setDefault('centers', null)
;
$resolver
->setDefined('role')
->addAllowedTypes('role', array(Role::class, 'null'))
->setDefault('role', null)
;
// add the default options
$resolver->setDefaults(array(
'class' => Event::class,
'choice_label' => function(Event $e) {
return $e->getDate()->format('d/m/Y, H:i') . ' → ' .
// $e->getType()->getName()['fr'] . ': ' . // display the type of event
$e->getName();
},
'placeholder' => 'Pick an event',
'attr' => array('class' => 'select2 '),
'choice_attr' => function(Event $e) {
return array('data-center' => $e->getCenter()->getId());
},
'choiceloader' => function(Options $options) {
$centers = $this->filterCenters($options);
return new EventChoiceLoader($this->eventRepository, $centers);
}
));
}
/**
* @return null|string
*/
public function getParent()
{
return EntityType::class;
}
/**
* @param \Symfony\Component\Form\FormView $view
* @param \Symfony\Component\Form\FormInterface $form
* @param array $options
*/
public function buildView(\Symfony\Component\Form\FormView $view, \Symfony\Component\Form\FormInterface $form, array $options)
{
$view->vars['attr']['data-person-picker'] = true;
$view->vars['attr']['data-select-interactive-loading'] = true;
$view->vars['attr']['data-search-url'] = $this->urlGenerator
->generate('chill_main_search', [ 'name' => EventSearch::NAME, '_format' => 'json' ]);
->generate('chill_main_search', ['name' => EventSearch::NAME, '_format' => 'json']);
$view->vars['attr']['data-placeholder'] = $this->translator->trans($options['placeholder']);
$view->vars['attr']['data-no-results-label'] = $this->translator->trans('select2.no_results');
$view->vars['attr']['data-error-load-label'] = $this->translator->trans('select2.error_loading');
$view->vars['attr']['data-searching-label'] = $this->translator->trans('select2.searching');
}
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
// add the possibles options for this type
$resolver
->setDefined('centers')
->addAllowedTypes('centers', ['array', Center::class, 'null'])
->setDefault('centers', null);
$resolver
->setDefined('role')
->addAllowedTypes('role', [Role::class, 'null'])
->setDefault('role', null);
// add the default options
$resolver->setDefaults([
'class' => Event::class,
'choice_label' => function (Event $e) {
return $e->getDate()->format('d/m/Y, H:i') . ' → ' .
// $e->getType()->getName()['fr'] . ': ' . // display the type of event
$e->getName();
},
'placeholder' => 'Pick an event',
'attr' => ['class' => 'select2 '],
'choice_attr' => function (Event $e) {
return ['data-center' => $e->getCenter()->getId()];
},
'choiceloader' => function (Options $options) {
$centers = $this->filterCenters($options);
return new EventChoiceLoader($this->eventRepository, $centers);
},
]);
}
/**
* @return string|null
*/
public function getParent()
{
return EntityType::class;
}
/**
* @param Options $options
* @return array
*/
protected function filterCenters(Options $options)
{
// option role
if ($options['role'] === NULL) {
if (null === $options['role']) {
$centers = array_map(
function (GroupCenter $g) {
return $g->getCenter();
@@ -184,31 +151,31 @@ class PickEventType extends AbstractType
}
// option center
if ($options['centers'] === NULL)
{
if (null === $options['centers']) {
// we select all selected centers
$selectedCenters = $centers;
} else {
$selectedCenters = array();
$selectedCenters = [];
$optionsCenters = is_array($options['centers']) ?
$options['centers'] : array($options['centers']);
$options['centers'] : [$options['centers']];
foreach ($optionsCenters as $c) {
// check that every member of the array is a center
if (!$c instanceof Center) {
throw new \RuntimeException('Every member of the "centers" '
. 'option must be an instance of '.Center::class);
throw new RuntimeException('Every member of the "centers" '
. 'option must be an instance of ' . Center::class);
}
if (!in_array($c->getId(), array_map(
function(Center $c) { return $c->getId();},
$centers))) {
function (Center $c) { return $c->getId(); },
$centers
))) {
throw new AccessDeniedException('The given center is not reachable');
}
$selectedCenters[] = $c;
}
}
return $selectedCenters;
}
}
}

View File

@@ -1,38 +1,23 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2016, 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/>.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form\Type;
use Chill\EventBundle\Entity\EventType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Chill\EventBundle\Entity\EventType;
/**
* Description of TranslatableEventType
*
* @author Champs-Libres Coop
* Description of TranslatableEventType.
*/
class PickEventTypeType extends AbstractType
{
@@ -40,34 +25,34 @@ class PickEventTypeType extends AbstractType
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
public function __construct(TranslatableStringHelper $helper)
{
$this->translatableStringHelper = $helper;
}
public function getParent()
{
return EntityType::class;
}
public function configureOptions(OptionsResolver $resolver)
{
$helper = $this->translatableStringHelper;
$resolver->setDefaults(
array(
[
'class' => EventType::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('et')
->where('et.active = true');
->where('et.active = true');
},
'choice_label' => function (EventType $t) use ($helper) {
return $helper->localize($t->getName());
},
'choice_attrs' => function (EventType $t) {
return array('data-link-category' => $t->getId());
}
)
return ['data-link-category' => $t->getId()];
},
]
);
}
public function getParent()
{
return EntityType::class;
}
}

View File

@@ -1,149 +1,128 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2016, 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/>.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form\Type;
use Chill\EventBundle\Entity\EventType;
use Chill\EventBundle\Entity\Role;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Chill\EventBundle\Entity\Role;
use Chill\EventBundle\Entity\EventType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Allow to pick a choice amongst different choices
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
* Allow to pick a choice amongst different choices.
*/
class PickRoleType extends AbstractType
{
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
*
* @var TranslatorInterface
*/
protected $translator;
/**
*
* @var EntityRepository
*/
protected $roleRepository;
/**
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
* @var TranslatorInterface
*/
protected $translator;
public function __construct(
TranslatableStringHelper $translatableStringHelper,
TranslatorInterface $translator,
EntityRepository $roleRepository
TranslatableStringHelper $translatableStringHelper,
TranslatorInterface $translator,
EntityRepository $roleRepository
) {
$this->translatableStringHelper = $translatableStringHelper;
$this->translator = $translator;
$this->roleRepository = $roleRepository;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// create copy for easier management
$qb = $options['query_builder'];
if ($options['event_type'] instanceof EventType) {
$options['query_builder']->where($qb->expr()->eq('r.type', ':event_type'))
->setParameter('event_type', $options['event_type']);
}
if ($options['active_only'] === true) {
$options['query_builder']->andWhere($qb->expr()->eq('r.active', ':active'))
->setParameter('active', true);
->setParameter('event_type', $options['event_type']);
}
if ($options['group_by'] === null) {
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) use ($options) {
if ($options['event_type'] === null) {
$form = $event->getForm();
$name = $form->getName();
$config = $form->getConfig();
$type = $config->getType()->getName();
$options = $config->getOptions();
$form->getParent()->add($name, $type, array_replace($options, array(
'group_by' => function(Role $r)
{ return $this->translatableStringHelper->localize($r->getType()->getName()); }
)));
}
if (true === $options['active_only']) {
$options['query_builder']->andWhere($qb->expr()->eq('r.active', ':active'))
->setParameter('active', true);
}
if (null === $options['group_by']) {
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($options) {
if (null === $options['event_type']) {
$form = $event->getForm();
$name = $form->getName();
$config = $form->getConfig();
$type = $config->getType()->getName();
$options = $config->getOptions();
$form->getParent()->add($name, $type, array_replace($options, [
'group_by' => function (Role $r) {
return $this->translatableStringHelper->localize($r->getType()->getName());
},
]));
}
}
);
);
}
}
public function configureOptions(OptionsResolver $resolver)
{
// create copy for use in Closure
$translatableStringHelper = $this->translatableStringHelper;
$translator = $this->translator;
$resolver
// add option "event_type"
->setDefined('event_type')
->setAllowedTypes('event_type', array('null', EventType::class))
->setAllowedTypes('event_type', ['null', EventType::class])
->setDefault('event_type', null)
// add option allow unactive
->setDefault('active_only', true)
->setAllowedTypes('active_only', array('boolean'))
;
->setAllowedTypes('active_only', ['boolean']);
$qb = $this->roleRepository->createQueryBuilder('r');
$resolver->setDefaults(array(
'class' => Role::class,
'query_builder' => $qb,
'group_by' => null,
'choice_attr' => function(Role $r) {
return array(
'data-event-type' => $r->getType()->getId(),
'data-link-category' => $r->getType()->getId()
);
},
'choice_label' => function(Role $r)
use ($translatableStringHelper, $translator) {
return $translatableStringHelper->localize($r->getName()).
$resolver->setDefaults([
'class' => Role::class,
'query_builder' => $qb,
'group_by' => null,
'choice_attr' => function (Role $r) {
return [
'data-event-type' => $r->getType()->getId(),
'data-link-category' => $r->getType()->getId(),
];
},
'choice_label' => function (Role $r) use ($translatableStringHelper, $translator) {
return $translatableStringHelper->localize($r->getName()) .
($r->getActive() === true ? '' :
' ('.$translator->trans('unactive').')');
}
));
' (' . $translator->trans('unactive') . ')');
},
]);
}
public function getParent()
{
return EntityType::class;

View File

@@ -1,152 +1,129 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2016, 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/>.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Form\Type;
use Chill\EventBundle\Entity\EventType;
use Chill\EventBundle\Entity\Status;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Chill\EventBundle\Entity\Status;
use Chill\EventBundle\Entity\EventType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Allow to pick amongst type
*
* parameters :
*
* Allow to pick amongst type.
*
* parameters :
*
* - event_type : restricts to a certain event type. Default null (= all event types)
* - active_only: restricts to active type only. Default true
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
*/
class PickStatusType extends AbstractType
{
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
*
* @var TranslatorInterface
*/
protected $translator;
/**
*
* @var EntityRepository
*/
protected $statusRepository;
/**
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
* @var TranslatorInterface
*/
protected $translator;
public function __construct(
TranslatableStringHelper $translatableStringHelper,
TranslatorInterface $translator,
EntityRepository $statusRepository
TranslatableStringHelper $translatableStringHelper,
TranslatorInterface $translator,
EntityRepository $statusRepository
) {
$this->translatableStringHelper = $translatableStringHelper;
$this->translator = $translator;
$this->statusRepository = $statusRepository;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$qb = $options['query_builder'];
if ($options['event_type'] instanceof EventType) {
$options['query_builder']->where($qb->expr()->eq('r.type', ':event_type'))
->setParameter('event_type', $options['event_type']);
->setParameter('event_type', $options['event_type']);
}
if ($options['active_only'] === true) {
if (true === $options['active_only']) {
$options['query_builder']->andWhere($qb->expr()->eq('r.active', ':active'))
->setParameter('active', true);
->setParameter('active', true);
}
if ($options['group_by'] === null && $options['event_type'] === null) {
if (null === $options['group_by'] && null === $options['event_type']) {
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) {
$form = $event->getForm();
$name = $form->getName();
$config = $form->getConfig();
$type = $config->getType()->getName();
$options = $config->getOptions();
$form->getParent()->add($name, $type, array_replace($options, array(
'group_by' => function(Status $s)
{ return $this->translatableStringHelper->localize($s->getType()->getName()); }
)));
}
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
$name = $form->getName();
$config = $form->getConfig();
$type = $config->getType()->getName();
$options = $config->getOptions();
$form->getParent()->add($name, $type, array_replace($options, [
'group_by' => function (Status $s) {
return $this->translatableStringHelper->localize($s->getType()->getName());
},
]));
}
);
}
}
public function configureOptions(OptionsResolver $resolver)
{
// create copy for use in Closure
$translatableStringHelper = $this->translatableStringHelper;
$translator = $this->translator;
$resolver
// add option "event_type"
->setDefined('event_type')
->setAllowedTypes('event_type', array('null', EventType::class))
->setAllowedTypes('event_type', ['null', EventType::class])
->setDefault('event_type', null)
// add option allow unactive
->setDefault('active_only', true)
->setAllowedTypes('active_only', array('boolean'))
;
->setAllowedTypes('active_only', ['boolean']);
$qb = $this->statusRepository->createQueryBuilder('r');
$resolver->setDefaults(array(
'class' => Status::class,
'query_builder' => $qb,
'group_by' => null,
'choice_attr' => function(Status $s) {
return array(
'data-event-type' => $s->getType()->getId(),
'data-link-category' => $s->getType()->getId()
);
},
'choice_label' => function(Status $s)
use ($translatableStringHelper, $translator) {
return $translatableStringHelper->localize($s->getName()).
$resolver->setDefaults([
'class' => Status::class,
'query_builder' => $qb,
'group_by' => null,
'choice_attr' => function (Status $s) {
return [
'data-event-type' => $s->getType()->getId(),
'data-link-category' => $s->getType()->getId(),
];
},
'choice_label' => function (Status $s) use ($translatableStringHelper, $translator) {
return $translatableStringHelper->localize($s->getName()) .
($s->getActive() === true ? '' :
' ('.$translator->trans('unactive').')');
}
));
' (' . $translator->trans('unactive') . ')');
},
]);
}
public function getParent()
{
return EntityType::class;

View File

@@ -1,28 +1,32 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Menu;
use Chill\EventBundle\Security\Authorization\EventVoter;
use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Knp\Menu\MenuItem;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Knp\Menu\MenuItem;
use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Chill\EventBundle\Security\Authorization\EventVoter;
class PersonMenuBuilder implements LocalMenuBuilderInterface
{
/**
*
* @var TranslatorInterface
*/
protected $translator;
/**
*
* @var AuthorizationCheckerInterface
*/
protected $authorizationChecker;
/**
* @var TranslatorInterface
*/
protected $translator;
public function __construct(
AuthorizationCheckerInterface $authorizationChecker,
TranslatorInterface $translator
@@ -30,29 +34,27 @@ class PersonMenuBuilder implements LocalMenuBuilderInterface
$this->authorizationChecker = $authorizationChecker;
$this->translator = $translator;
}
public function buildMenu($menuId, MenuItem $menu, array $parameters)
{
/* @var $person \Chill\PersonBundle\Entity\Person */
$person = $parameters['person'] ?? null;
$person = $parameters['person'] ?? null;
if ($this->authorizationChecker->isGranted(EventVoter::SEE, $person)) {
$menu->addChild($this->translator->trans('Events participation'), [
'route' => 'chill_event__list_by_person',
'routeParameters' => [
'person_id' => $person->getId()
]
'person_id' => $person->getId(),
],
])
->setExtras([
'order' => 500
]);
->setExtras([
'order' => 500,
]);
}
}
public static function getMenuIds(): array
{
return [ 'person' ];
return ['person'];
}
}
}

View File

@@ -1,22 +1,10 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2014-2019, 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Repository;
@@ -24,12 +12,8 @@ namespace Chill\EventBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* Class EventRepository
*
* @package Chill\EventBundle\Repository
* @author Mathieu Jaumotte jaum_mathieu@collectifs.net
* Class EventRepository.
*/
class EventRepository extends EntityRepository
{
}

View File

@@ -1,22 +1,10 @@
<?php
/*
/**
* Chill is a software for social workers
*
* Copyright (C) 2014-2019, 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Repository;
@@ -24,20 +12,18 @@ namespace Chill\EventBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* Class ParticipationRepository
*
* @package Chill\EventBundle\Repository
* @author Mathieu Jaumotte jaum_mathieu@collectifs.net
* Class ParticipationRepository.
*/
class ParticipationRepository extends EntityRepository
{
/**
* Count number of participations per person
* Count number of participations per person.
*
* @param $person_id
* @return mixed
*
* @throws \Doctrine\ORM\NonUniqueResultException
*
* @return mixed
*/
public function countByPerson($person_id)
{
@@ -46,18 +32,17 @@ class ParticipationRepository extends EntityRepository
->where('p.id = :person_id')
->setParameter(':person_id', $person_id)
->getQuery()
->getSingleScalarResult()
;
->getSingleScalarResult();
}
/**
* Return paginated participations for a person and in reachables circles
* Return paginated participations for a person and in reachables circles.
*
* @param $person_id
* @param $reachablesCircles
* @param $first
* @param $max
*
* @return mixed
*/
public function findByPersonInCircle($person_id, $reachablesCircles, $first, $max)
@@ -67,17 +52,13 @@ class ParticipationRepository extends EntityRepository
->where('p.person = :person_id')
->andWhere('e.circle IN (:reachable_circles)')
->orderBy('e.date', 'ASC')
->setParameters(array(
->setParameters([
':person_id' => $person_id,
':reachable_circles' => $reachablesCircles
))
':reachable_circles' => $reachablesCircles,
])
->setFirstResult($first)
->setMaxResults($max)
->getQuery()
->getResult()
;
->getResult();
}
}

View File

@@ -1,13 +1,36 @@
<?php
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class AppKernel extends Kernel
{
/**
* @return string
*/
public function getCacheDir()
{
return sys_get_temp_dir() . '/ChillEventBundle/cache';
}
/**
* @return string
*/
public function getLogDir()
{
return sys_get_temp_dir() . '/ChillEventBundle/logs';
}
public function registerBundles()
{
return array(
{
return [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Chill\MainBundle\ChillMainBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
@@ -19,28 +42,12 @@ class AppKernel extends Kernel
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Chill\PersonBundle\ChillPersonBundle(),
new Chill\CustomFieldsBundle\ChillCustomFieldsBundle(),
new \Chill\EventBundle\ChillEventBundle,
);
}
new \Chill\EventBundle\ChillEventBundle(),
];
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
/**
* @return string
*/
public function getCacheDir()
{
return sys_get_temp_dir().'/ChillEventBundle/cache';
}
/**
* @return string
*/
public function getLogDir()
{
return sys_get_temp_dir().'/ChillEventBundle/logs';
}
{
$loader->load(__DIR__ . '/config/config_' . $this->getEnvironment() . '.yml');
}
}

View File

@@ -1,8 +1,14 @@
<?php
if (!is_file($autoloadFile = __DIR__.'/../../vendor/autoload.php')) {
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
if (!is_file($autoloadFile = __DIR__ . '/../../vendor/autoload.php')) {
throw new \LogicException('Could not find autoload.php in vendor/. Did you run "composer install --dev"?');
}
require $autoloadFile;

View File

@@ -1,18 +1,24 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Search;
use Chill\EventBundle\Entity\Event;
use Chill\MainBundle\Search\AbstractSearch;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Templating\EngineInterface as TemplatingEngine;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Security\Core\Role\Role;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Search\AbstractSearch;
use Chill\MainBundle\Search\SearchInterface;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Templating\EngineInterface as TemplatingEngine;
/**
* Search within Events.
@@ -26,208 +32,206 @@ use Chill\MainBundle\Search\SearchInterface;
* Default terms search within the name, but the term "name" has precedence. This
* means that if the search string is `@event xyz name:"abc"`, the searched
* string will be "abc" and not xyz
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
*/
class EventSearch extends AbstractSearch
{
public const NAME = 'event_regular';
/**
*
* @var EntityRepository
*/
private $er;
/**
*
* @var \Chill\MainBundle\Entity\User
*/
private $user;
/**
*
* @var AuthorizationHelper
*/
private $helper;
/**
*
* @var TemplatingEngine
*/
private $templating;
/**
*
* @var PaginatorFactory
*/
private $paginationFactory;
const NAME = 'event_regular';
/**
* @var TemplatingEngine
*/
private $templating;
/**
* @var \Chill\MainBundle\Entity\User
*/
private $user;
public function __construct(
TokenStorageInterface $tokenStorage,
EntityRepository $eventRepository,
AuthorizationHelper $authorizationHelper,
TemplatingEngine $templating,
PaginatorFactory $paginatorFactory
)
{
TokenStorageInterface $tokenStorage,
EntityRepository $eventRepository,
AuthorizationHelper $authorizationHelper,
TemplatingEngine $templating,
PaginatorFactory $paginatorFactory
) {
$this->user = $tokenStorage->getToken()->getUser();
$this->er = $eventRepository;
$this->helper = $authorizationHelper;
$this->templating = $templating;
$this->paginationFactory = $paginatorFactory;
}
public function supports($domain, $format)
{
return 'event' === $domain or 'events' === $domain;
}
public function isActiveByDefault()
{
return true;
}
public function getOrder()
{
return 3000;
}
public function renderResult(array $terms, $start = 0, $limit = 50,
array $options = array(), $format = 'html')
public function isActiveByDefault()
{
return true;
}
public function renderResult(
array $terms,
$start = 0,
$limit = 50,
array $options = [],
$format = 'html'
)
{
$total = $this->count($terms);
$paginator = $this->paginationFactory->create($total);
if ($format === 'html') {
return $this->templating->render('ChillEventBundle:Event:list.html.twig',
array(
if ('html' === $format) {
return $this->templating->render(
'ChillEventBundle:Event:list.html.twig',
[
'events' => $this->search($terms, $start, $limit, $options),
'pattern' => $this->recomposePattern($terms, $this->getAvailableTerms(), $terms['_domain']),
'total' => $total,
'start' => $start,
'preview' => $options[SearchInterface::SEARCH_PREVIEW_OPTION],
'paginator' => $paginator,
'search_name' => self::NAME
));
'search_name' => self::NAME,
]
);
}
else if ($format === 'json') {
if ('json' === $format) {
$results = [];
$search = $this->search($terms, $start, $limit, $options);
foreach ($search as $item) {
$results[] = [
'id' => $item->getId(),
'text' => $item->getDate()->format('d/m/Y, H:i') . ' → ' .
// $item->getType()->getName()['fr'] . ': ' . // display the type of event
$item->getName()
$item->getName(),
];
}
return [
'results' => $results,
'pagination' => [
'more' => $paginator->hasNextPage()
]
'more' => $paginator->hasNextPage(),
],
];
}
}
protected function getAvailableTerms()
public function supports($domain, $format)
{
return array('date-from', 'date-to', 'name', 'date');
return 'event' === $domain or 'events' === $domain;
}
protected function search(array $terms, $start, $limit, $options)
{
$qb = $this->er->createQueryBuilder('e');
$qb->select('e');
$this->composeQuery($qb, $terms)
->setMaxResults($limit)
->setFirstResult($start)
->orderBy('e.date', 'DESC')
;
return $qb->getQuery()->getResult();
}
protected function count(array $terms)
{
$qb = $this->er->createQueryBuilder('e');
$qb->select('COUNT(e)');
$this->composeQuery($qb, $terms)
;
return $qb->getQuery()->getSingleScalarResult();
}
protected function composeQuery(QueryBuilder &$qb, $terms)
{
// add security clauses
$reachableCenters = $this->helper
->getReachableCenters($this->user, new Role('CHILL_EVENT_SEE'));
->getReachableCenters($this->user, new Role('CHILL_EVENT_SEE'));
if (count($reachableCenters) === 0) {
// add a clause to block all events
$where = $qb->expr()->isNull('e.center');
$qb->andWhere($where);
} else {
$n = 0;
$orWhere = $qb->expr()->orX();
foreach ($reachableCenters as $center) {
$circles = $this->helper->getReachableScopes($this->user,
new Role('CHILL_EVENT_SEE'), $center);
$circles = $this->helper->getReachableScopes(
$this->user,
new Role('CHILL_EVENT_SEE'),
$center
);
$where = $qb->expr()->andX(
$qb->expr()->eq('e.center', ':center_'.$n),
$qb->expr()->in('e.circle', ':circle_'.$n)
);
$qb->setParameter('center_'.$n, $center);
$qb->setParameter('circle_'.$n, $circles);
$qb->expr()->eq('e.center', ':center_' . $n),
$qb->expr()->in('e.circle', ':circle_' . $n)
);
$qb->setParameter('center_' . $n, $center);
$qb->setParameter('circle_' . $n, $circles);
$orWhere->add($where);
}
$qb->andWhere($orWhere);
}
if (
(isset($terms['name']) OR isset($terms['_default']))
AND
(!empty($terms['name']) OR !empty($terms['_default']))) {
(isset($terms['name']) or isset($terms['_default']))
and (!empty($terms['name']) or !empty($terms['_default']))) {
// the form with name:"xyz" has precedence
$name = isset($terms['name']) ? $terms['name'] : $terms['_default'];
$name = $terms['name'] ?? $terms['_default'];
$where = $qb->expr()->like('UNACCENT(LOWER(e.name))', ':name');
$qb->setParameter('name', '%'.$name.'%');
$qb->setParameter('name', '%' . $name . '%');
$qb->andWhere($where);
}
if (isset($terms['date'])) {
$date = $this->parseDate($terms['date']);
$where = $qb->expr()->eq('e.date', ':date');
$qb->setParameter('date', $date);
$qb->andWhere($where);
}
if (isset($terms['date-from'])) {
$date = $this->parseDate($terms['date-from']);
$where = $qb->expr()->gte('e.date', ':datefrom');
$qb->setParameter('datefrom', $date);
$qb->andWhere($where);
}
if (isset($terms['date-to'])) {
$date = $this->parseDate($terms['date-to']);
$where = $qb->expr()->lte('e.date', ':dateto');
$qb->setParameter('dateto', $date);
$qb->andWhere($where);
}
return $qb;
}
protected function count(array $terms)
{
$qb = $this->er->createQueryBuilder('e');
$qb->select('COUNT(e)');
$this->composeQuery($qb, $terms);
return $qb->getQuery()->getSingleScalarResult();
}
protected function getAvailableTerms()
{
return ['date-from', 'date-to', 'name', 'date'];
}
protected function search(array $terms, $start, $limit, $options)
{
$qb = $this->er->createQueryBuilder('e');
$qb->select('e');
$this->composeQuery($qb, $terms)
->setMaxResults($limit)
->setFirstResult($start)
->orderBy('e.date', 'DESC');
return $qb->getQuery()->getResult();
}
}

View File

@@ -1,65 +1,56 @@
<?php
/*
* Copyright (C) 2020 Champs Libres Cooperative <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Security\Authorization;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\EventBundle\Entity\Event;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Role\Role;
use Psr\Log\LoggerInterface;
/**
* Description of EventVoter
*
* @author Mathieu Jaumotte <jaum_mathieu@collectifs.net>
* @author Champs Libres <info@champs-libres.coop>
* Description of EventVoter.
*/
class EventVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
const SEE = 'CHILL_EVENT_SEE';
const SEE_DETAILS = 'CHILL_EVENT_SEE_DETAILS';
const CREATE = 'CHILL_EVENT_CREATE';
const UPDATE = 'CHILL_EVENT_UPDATE';
public const CREATE = 'CHILL_EVENT_CREATE';
const ROLES = [
public const ROLES = [
self::SEE,
self::SEE_DETAILS,
self::CREATE,
self::UPDATE
self::UPDATE,
];
/**
* @var AuthorizationHelper
*/
protected $authorizationHelper;
public const SEE = 'CHILL_EVENT_SEE';
public const SEE_DETAILS = 'CHILL_EVENT_SEE_DETAILS';
public const UPDATE = 'CHILL_EVENT_UPDATE';
/**
* @var AccessDecisionManagerInterface
*/
protected $accessDecisionManager;
/**
* @var AuthorizationHelper
*/
protected $authorizationHelper;
/**
* @var LoggerInterface
*/
@@ -69,65 +60,12 @@ class EventVoter extends AbstractChillVoter implements ProvideRoleHierarchyInter
AccessDecisionManagerInterface $accessDecisionManager,
AuthorizationHelper $authorizationHelper,
LoggerInterface $logger
)
{
) {
$this->accessDecisionManager = $accessDecisionManager;
$this->authorizationHelper = $authorizationHelper;
$this->logger = $logger;
}
public function supports($attribute, $subject)
{
return ($subject instanceof Event && in_array($attribute, self::ROLES))
||
($subject instanceof Person && \in_array($attribute, [ self::CREATE, self::SEE ]))
||
(NULL === $subject && $attribute === self::SEE )
;
}
/**
*
* @param string $attribute
* @param Event $subject
* @param TokenInterface $token
* @return boolean
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$this->logger->debug(sprintf("Voting from %s class", self::class));
if (!$token->getUser() instanceof User) {
return false;
}
if ($subject instanceof Event) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
} elseif ($subject instanceof Person) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
} else {
// subject is null. We check that at least one center is reachable
$centers = $this->authorizationHelper
->getReachableCenters($token->getUser(), new Role($attribute));
return count($centers) > 0;
}
if (!$this->accessDecisionManager->decide($token, [PersonVoter::SEE], $person)) {
return false;
}
return $this->authorizationHelper->userHasAccess(
$token->getUser(),
$subject,
$attribute
);
}
public function getRoles(): array
{
return self::ROLES;
@@ -136,7 +74,7 @@ class EventVoter extends AbstractChillVoter implements ProvideRoleHierarchyInter
public function getRolesWithHierarchy(): array
{
return [
'Event' => self::ROLES
'Event' => self::ROLES,
];
}
@@ -145,4 +83,49 @@ class EventVoter extends AbstractChillVoter implements ProvideRoleHierarchyInter
return [];
}
public function supports($attribute, $subject)
{
return ($subject instanceof Event && in_array($attribute, self::ROLES))
|| ($subject instanceof Person && \in_array($attribute, [self::CREATE, self::SEE]))
|| (null === $subject && self::SEE === $attribute);
}
/**
* @param string $attribute
* @param Event $subject
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$this->logger->debug(sprintf('Voting from %s class', self::class));
if (!$token->getUser() instanceof User) {
return false;
}
if ($subject instanceof Event) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
}
if ($subject instanceof Person) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
}
// subject is null. We check that at least one center is reachable
$centers = $this->authorizationHelper
->getReachableCenters($token->getUser(), new Role($attribute));
return count($centers) > 0;
if (!$this->accessDecisionManager->decide($token, [PersonVoter::SEE], $person)) {
return false;
}
return $this->authorizationHelper->userHasAccess(
$token->getUser(),
$subject,
$attribute
);
}
}

View File

@@ -1,64 +1,53 @@
<?php
/*
* Copyright (C) 2020 Champs-Libres <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Security\Authorization;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\EventBundle\Entity\Participation;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Security\ProvideRoleHierarchyInterface;
use Chill\PersonBundle\Entity\Person;
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\Role\Role;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Role\Role;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ParticipationVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
const SEE = 'CHILL_EVENT_PARTICIPATION_SEE';
const SEE_DETAILS = 'CHILL_EVENT_PARTICIPATION_SEE_DETAILS';
const CREATE = 'CHILL_EVENT_PARTICIPATION_CREATE';
const UPDATE = 'CHILL_EVENT_PARTICIPATION_UPDATE';
public const CREATE = 'CHILL_EVENT_PARTICIPATION_CREATE';
const ROLES = [
public const ROLES = [
self::SEE,
self::SEE_DETAILS,
self::CREATE,
self::UPDATE
self::UPDATE,
];
/**
* @var AuthorizationHelper
*/
protected $authorizationHelper;
public const SEE = 'CHILL_EVENT_PARTICIPATION_SEE';
public const SEE_DETAILS = 'CHILL_EVENT_PARTICIPATION_SEE_DETAILS';
public const UPDATE = 'CHILL_EVENT_PARTICIPATION_UPDATE';
/**
* @var AccessDecisionManagerInterface
*/
protected $accessDecisionManager;
/**
* @var AuthorizationHelper
*/
protected $authorizationHelper;
/**
* @var LoggerInterface
*/
@@ -68,65 +57,12 @@ class ParticipationVoter extends AbstractChillVoter implements ProvideRoleHierar
AccessDecisionManagerInterface $accessDecisionManager,
AuthorizationHelper $authorizationHelper,
LoggerInterface $logger
)
{
) {
$this->accessDecisionManager = $accessDecisionManager;
$this->authorizationHelper = $authorizationHelper;
$this->logger = $logger;
}
public function supports($attribute, $subject)
{
return ($subject instanceof Participation && in_array($attribute, self::ROLES))
||
($subject instanceof Person && \in_array($attribute, [ self::CREATE, self::SEE ]))
||
(NULL === $subject && $attribute === self::SEE )
;
}
/**
*
* @param string $attribute
* @param Participation $subject
* @param TokenInterface $token
* @return boolean
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$this->logger->debug(sprintf("Voting from %s class", self::class));
if (!$token->getUser() instanceof User) {
return false;
}
if ($subject instanceof Participation) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
} elseif ($subject instanceof Person) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
} else {
// subject is null. We check that at least one center is reachable
$centers = $this->authorizationHelper
->getReachableCenters($token->getUser(), new Role($attribute));
return count($centers) > 0;
}
if (!$this->accessDecisionManager->decide($token, [PersonVoter::SEE], $person)) {
return false;
}
return $this->authorizationHelper->userHasAccess(
$token->getUser(),
$subject,
$attribute
);
}
public function getRoles(): array
{
return self::ROLES;
@@ -135,7 +71,7 @@ class ParticipationVoter extends AbstractChillVoter implements ProvideRoleHierar
public function getRolesWithHierarchy(): array
{
return [
'Event' => self::ROLES
'Event' => self::ROLES,
];
}
@@ -144,4 +80,49 @@ class ParticipationVoter extends AbstractChillVoter implements ProvideRoleHierar
return [];
}
public function supports($attribute, $subject)
{
return ($subject instanceof Participation && in_array($attribute, self::ROLES))
|| ($subject instanceof Person && \in_array($attribute, [self::CREATE, self::SEE]))
|| (null === $subject && self::SEE === $attribute);
}
/**
* @param string $attribute
* @param Participation $subject
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$this->logger->debug(sprintf('Voting from %s class', self::class));
if (!$token->getUser() instanceof User) {
return false;
}
if ($subject instanceof Participation) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
}
if ($subject instanceof Person) {
return $this->authorizationHelper->userHasAccess($token->getUser(), $subject, $attribute);
}
// subject is null. We check that at least one center is reachable
$centers = $this->authorizationHelper
->getReachableCenters($token->getUser(), new Role($attribute));
return count($centers) > 0;
if (!$this->accessDecisionManager->decide($token, [PersonVoter::SEE], $person)) {
return false;
}
return $this->authorizationHelper->userHasAccess(
$token->getUser(),
$subject,
$attribute
);
}
}

View File

@@ -1,16 +1,27 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class EventControllerTest extends WebTestCase
{
public function testSkipped()
{
$this->markTestSkipped();
}
/*
public function testCompleteScenario()
{
@@ -56,5 +67,5 @@ class EventControllerTest extends WebTestCase
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
*/
}

View File

@@ -1,15 +1,27 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class EventTypeControllerTest extends WebTestCase
{
public function testSkipped()
{
$this->markTestSkipped();
}
/*
public function testCompleteScenario()
{
@@ -55,5 +67,5 @@ class EventTypeControllerTest extends WebTestCase
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
*/
}

View File

@@ -1,20 +1,10 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Tests\Controller;
@@ -22,263 +12,220 @@ namespace Chill\EventBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Test the creation of participation controller
*
* Test the creation of participation controller.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class ParticipationControllerTest extends WebTestCase
{
/**
*
* @var \Symfony\Component\BrowserKit\Client
*/
protected $client;
/**
*
* @var \Doctrine\ORM\EntityManagerInterface
*/
protected $em;
/**
* Keep a cache for each person id given by the function getRandomPerson.
*
*
* You may ask to ignore some people by adding their id to the array.
*
*
* This is reset by setUp().
*
* @var int[]
* @var int[]
*/
private $personsIdsCache = array();
private $personsIdsCache = [];
public function setUp()
{
self::bootKernel();
$this->client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR'
));
$this->client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR',
]);
$container = self::$kernel->getContainer();
$this->em = $container->get('doctrine.orm.entity_manager')
;
$this->personsIdsCache = array();
$this->em = $container->get('doctrine.orm.entity_manager');
$this->personsIdsCache = [];
}
/**
*
*
* @return \Chill\EventBundle\Entity\Event
*/
protected function getRandomEvent($centerName = 'Center A', $circleName = 'social')
{
$center = $this->em->getRepository('ChillMainBundle:Center')
->findByName($centerName);
$circles = $this->em->getRepository('ChillMainBundle:Scope')
->findAll();
array_filter($circles, function($circle) use ($circleName) {
return in_array($circleName, $circle->getName());
});
$circle = $circles[0];
$events = $this->em->getRepository('ChillEventBundle:Event')
->findBy(array('center' => $center, 'circle' => $circle));
return $events[array_rand($events)];
}
/**
* Return a random event only if he has more than one participation.
*
* @param string $centerName
* @param type $circleName
* @return \Chill\EventBundle\Entity\Event
*/
protected function getRandomEventWithMultipleParticipations(
$centerName = 'Center A',
$circleName = 'social')
{
$event = $this->getRandomEvent($centerName, $circleName);
return $event->getParticipations()->count() > 1 ?
$event :
$this->getRandomEventWithMultipleParticipations($centerName, $circleName);
}
/**
* Returns a person randomly.
*
* This function does not give the same person twice
* for each test.
*
* You may ask to ignore some people by adding their id to the property
* `$this->personsIdsCache`
*
* @param string $centerName
* @return \Chill\PersonBundle\Entity\Person
*/
protected function getRandomPerson($centerName = 'Center A')
{
$center = $this->em->getRepository('ChillMainBundle:Center')
->findByName($centerName);
$persons = $this->em->getRepository('ChillPersonBundle:Person')
->findBy(array('center' => $center));
$person = $persons[array_rand($persons)];
if (in_array($person->getId(), $this->personsIdsCache)) {
return $this->getRandomPerson($centerName); // we try another time
} else {
$this->personsIdsCache[] = $person->getId();
return $person;
}
}
public function testNewActionWrongParameters()
{
$event = $this->getRandomEvent();
$person = $this->getRandomPerson();
// missing person_id or persons_ids
$this->client->request('GET', '/fr/event/participation/new',
array(
'event_id' => $event->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test that /fr/event/participation/new fail if "
. "both person_id and persons_ids are missing");
// having both person_id and persons_ids
$this->client->request('GET', '/fr/event/participation/new',
array(
'event_id' => $event->getId(),
'persons_ids' => implode(',', array(
$this->getRandomPerson()->getId(),
$this->getRandomPerson()->getId()
)),
'person_id' => $person->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"test that /fr/event/participation/new fail if both person_id and "
. "persons_ids are set");
// missing event_id
$this->client->request('GET', '/fr/event/participation/new',
array(
'person_id' => $person->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test that /fr/event/participation/new fails if event_id is missing");
// persons_ids with wrong content
$this->client->request('GET', '/fr/event/participation/new',
array(
'persons_ids' => 'a,b,531',
'event_id' => $event->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test that /fr/event/participation/new fails if persons_ids has wrong content");
}
/**
* This method test participation creation with wrong parameters.
*
*
* Those request should fail before any processing.
*/
public function testCreateActionWrongParameters()
{
$event = $this->getRandomEvent();
$person = $this->getRandomPerson();
// missing person_id or persons_ids
$this->client->request('GET', '/fr/event/participation/create',
array(
'event_id' => $event->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test that /fr/event/participation/create fail if "
. "both person_id and persons_ids are missing");
$this->client->request(
'GET',
'/fr/event/participation/create',
[
'event_id' => $event->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test that /fr/event/participation/create fail if '
. 'both person_id and persons_ids are missing'
);
// having both person_id and persons_ids
$this->client->request('GET', '/fr/event/participation/create',
array(
'event_id' => $event->getId(),
'persons_ids' => implode(',', array(
$this->getRandomPerson()->getId(),
$this->getRandomPerson()->getId()
)),
'person_id' => $person->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"test that /fr/event/participation/create fail if both person_id and "
. "persons_ids are set");
$this->client->request(
'GET',
'/fr/event/participation/create',
[
'event_id' => $event->getId(),
'persons_ids' => implode(',', [
$this->getRandomPerson()->getId(),
$this->getRandomPerson()->getId(),
]),
'person_id' => $person->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'test that /fr/event/participation/create fail if both person_id and '
. 'persons_ids are set'
);
// missing event_id
$this->client->request('GET', '/fr/event/participation/create',
array(
'person_id' => $person->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test that /fr/event/participation/create fails if event_id is missing");
$this->client->request(
'GET',
'/fr/event/participation/create',
[
'person_id' => $person->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test that /fr/event/participation/create fails if event_id is missing'
);
// persons_ids with wrong content
$this->client->request('GET', '/fr/event/participation/create',
array(
'persons_ids' => 'a,b,531',
'event_id' => $event->getId()
));
$this->assertEquals(400, $this->client->getResponse()->getStatusCode(),
"Test that /fr/event/participation/create fails if persons_ids has wrong content");
$this->client->request(
'GET',
'/fr/event/participation/create',
[
'persons_ids' => 'a,b,531',
'event_id' => $event->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test that /fr/event/participation/create fails if persons_ids has wrong content'
);
}
public function testNewSingleAction()
public function testEditMultipleAction()
{
/* @var $event \Chill\EventBundle\Entity\Event */
$event = $this->getRandomEventWithMultipleParticipations();
$crawler = $this->client->request('GET', '/fr/event/participation/' . $event->getId() .
'/edit_multiple');
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
$button = $crawler->selectButton('Mettre à jour');
$this->assertEquals(1, $button->count(), "test the form with button 'mettre à jour' exists ");
$this->client->submit($button->form(), [
'form[participations][0][role]' => $event->getType()->getRoles()->first()->getId(),
'form[participations][0][status]' => $event->getType()->getStatuses()->first()->getId(),
'form[participations][1][role]' => $event->getType()->getRoles()->last()->getId(),
'form[participations][1][status]' => $event->getType()->getStatuses()->last()->getId(),
]);
$this->assertTrue($this->client->getResponse()
->isRedirect('/fr/event/event/' . $event->getId() . '/show'));
}
public function testNewActionWrongParameters()
{
$event = $this->getRandomEvent();
// record the number of participation for the event
$nbParticipations = $event->getParticipations()->count();
$person = $this->getRandomPerson();
$crawler = $this->client->request('GET', '/fr/event/participation/new',
array(
'person_id' => $person->getId(),
'event_id' => $event->getId()
));
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(),
"test that /fr/event/participation/new is successful");
$button = $crawler->selectButton('Créer');
$this->assertNotNull($button, "test the form with button 'Créer' exists");
$this->client->submit($button->form(), array(
'participation[role]' => $event->getType()->getRoles()->first()->getId(),
'participation[status]' => $event->getType()->getStatuses()->first()->getId()
));
$this->assertTrue($this->client->getResponse()->isRedirect());
$crawler = $this->client->followRedirect();
$span = $crawler->filter('table td span.entity-person a:contains("'
.$person->getFirstName().'"):contains("'.$person->getLastname().'")');
$this->assertGreaterThan(0, count($span));
// as the container has reloaded, reload the event
$event = $this->em->getRepository('ChillEventBundle:Event')->find($event->getId());
$this->em->refresh($event);
$this->assertEquals($nbParticipations + 1, $event->getParticipations()->count());
// missing person_id or persons_ids
$this->client->request(
'GET',
'/fr/event/participation/new',
[
'event_id' => $event->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test that /fr/event/participation/new fail if '
. 'both person_id and persons_ids are missing'
);
// having both person_id and persons_ids
$this->client->request(
'GET',
'/fr/event/participation/new',
[
'event_id' => $event->getId(),
'persons_ids' => implode(',', [
$this->getRandomPerson()->getId(),
$this->getRandomPerson()->getId(),
]),
'person_id' => $person->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'test that /fr/event/participation/new fail if both person_id and '
. 'persons_ids are set'
);
// missing event_id
$this->client->request(
'GET',
'/fr/event/participation/new',
[
'person_id' => $person->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test that /fr/event/participation/new fails if event_id is missing'
);
// persons_ids with wrong content
$this->client->request(
'GET',
'/fr/event/participation/new',
[
'persons_ids' => 'a,b,531',
'event_id' => $event->getId(),
]
);
$this->assertEquals(
400,
$this->client->getResponse()->getStatusCode(),
'Test that /fr/event/participation/new fails if persons_ids has wrong content'
);
}
public function testNewMultipleAction()
{
$event = $this->getRandomEvent();
@@ -286,79 +233,91 @@ class ParticipationControllerTest extends WebTestCase
$nbParticipations = $event->getParticipations()->count();
// make ignore the people already in the event from the function getRandomPerson
$this->personsIdsCache = array_merge(
$this->personsIdsCache,
$event->getParticipations()->map(
function($p) { return $p->getPerson()->getId(); }
)
$this->personsIdsCache,
$event->getParticipations()->map(
function ($p) { return $p->getPerson()->getId(); }
)
->toArray()
);
);
// get some random people
$person1 = $this->getRandomPerson();
$person2 = $this->getRandomPerson();
$crawler = $this->client->request('GET', '/fr/event/participation/new',
array(
'persons_ids' => implode(',', array($person1->getId(), $person2->getId())),
'event_id' => $event->getId()
));
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(),
"test that /fr/event/participation/new is successful");
$crawler = $this->client->request(
'GET',
'/fr/event/participation/new',
[
'persons_ids' => implode(',', [$person1->getId(), $person2->getId()]),
'event_id' => $event->getId(),
]
);
$this->assertEquals(
200,
$this->client->getResponse()->getStatusCode(),
'test that /fr/event/participation/new is successful'
);
$button = $crawler->selectButton('Créer');
$this->assertNotNull($button, "test the form with button 'Créer' exists");
$this->client->submit($button->form(), array(
'form' => array(
'participations' => array(
0 => array(
$this->client->submit($button->form(), [
'form' => [
'participations' => [
0 => [
'role' => $event->getType()->getRoles()->first()->getId(),
'status' => $event->getType()->getStatuses()->first()->getId()
),
1 => array(
'status' => $event->getType()->getStatuses()->first()->getId(),
],
1 => [
'role' => $event->getType()->getRoles()->first()->getId(),
'status' => $event->getType()->getStatuses()->first()->getId()
),
)
)
));
'status' => $event->getType()->getStatuses()->first()->getId(),
],
],
],
]);
$this->assertTrue($this->client->getResponse()->isRedirect());
$crawler = $this->client->followRedirect();
$span1 = $crawler->filter('table td span.entity-person a:contains("'
.$person1->getFirstName().'"):contains("'.$person1->getLastname().'")');
. $person1->getFirstName() . '"):contains("' . $person1->getLastname() . '")');
$this->assertGreaterThan(0, count($span1));
$span2 = $crawler->filter('table td span.entity-person a:contains("'
.$person2->getFirstName().'"):contains("'.$person2->getLastname().'")');
. $person2->getFirstName() . '"):contains("' . $person2->getLastname() . '")');
$this->assertGreaterThan(0, count($span2));
// as the container has reloaded, reload the event
$event = $this->em->getRepository('ChillEventBundle:Event')->find($event->getId());
$this->em->refresh($event);
$this->assertEquals($nbParticipations + 2, $event->getParticipations()->count());
}
public function testNewMultipleWithAllPeopleParticipating()
{
$event = $this->getRandomEventWithMultipleParticipations();
$persons_id = implode(',', $event->getParticipations()->map(
function($p) { return $p->getPerson()->getId(); }
)->toArray());
$crawler = $this->client->request('GET', '/fr/event/participation/new',
array(
'persons_ids' => $persons_id,
'event_id' => $event->getId()
));
$this->assertEquals(302, $this->client->getResponse()->getStatusCode(),
"test that /fr/event/participation/new is redirecting");
function ($p) { return $p->getPerson()->getId(); }
)->toArray());
$crawler = $this->client->request(
'GET',
'/fr/event/participation/new',
[
'persons_ids' => $persons_id,
'event_id' => $event->getId(),
]
);
$this->assertEquals(
302,
$this->client->getResponse()->getStatusCode(),
'test that /fr/event/participation/new is redirecting'
);
}
public function testNewMultipleWithSomePeopleParticipating()
{
$event = $this->getRandomEventWithMultipleParticipations();
@@ -366,83 +325,194 @@ class ParticipationControllerTest extends WebTestCase
$nbParticipations = $event->getParticipations()->count();
// get the persons_id participating on this event
$persons_id = $event->getParticipations()->map(
function($p) { return $p->getPerson()->getId(); }
)->toArray();
function ($p) { return $p->getPerson()->getId(); }
)->toArray();
// exclude the existing persons_ids from the new person
$this->personsIdsCache = array_merge($this->personsIdsCache, $persons_id);
// get a random person
$newPerson = $this->getRandomPerson();
// build the `persons_ids` parameter
$persons_ids_string = implode(',', array_merge($persons_id,
array($newPerson->getId())));
$crawler = $this->client->request('GET', '/fr/event/participation/new',
array(
'persons_ids' => $persons_ids_string,
'event_id' => $event->getId()
));
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(),
"test that /fr/event/participation/new is successful");
$persons_ids_string = implode(',', array_merge(
$persons_id,
[$newPerson->getId()]
));
$crawler = $this->client->request(
'GET',
'/fr/event/participation/new',
[
'persons_ids' => $persons_ids_string,
'event_id' => $event->getId(),
]
);
$this->assertEquals(
200,
$this->client->getResponse()->getStatusCode(),
'test that /fr/event/participation/new is successful'
);
// count that the one UL contains the new person string
$firstPerson = $event->getParticipations()->first()->getPerson();
$ul = $crawler->filter('ul:contains("'.$firstPerson->getLastName().'")'
. ':contains("'.$firstPerson->getFirstName().'")');
$this->assertEquals(1, $ul->count(),
"assert an ul containing the name of ignored people is present");
$this->assertEquals($event->getParticipations()->count(), $ul->children()->count(),
"assert the li listing ignored people has the correct number");
$ul = $crawler->filter('ul:contains("' . $firstPerson->getLastName() . '")'
. ':contains("' . $firstPerson->getFirstName() . '")');
$this->assertEquals(
1,
$ul->count(),
'assert an ul containing the name of ignored people is present'
);
$this->assertEquals(
$event->getParticipations()->count(),
$ul->children()->count(),
'assert the li listing ignored people has the correct number'
);
// test a form is present on the page
$button = $crawler->selectButton('Créer');
$this->assertNotNull($button, "test the form with button 'Créer' exists");
// submit the form
$this->client->submit($button->form(), array(
$this->client->submit($button->form(), [
'participation[role]' => $event->getType()->getRoles()->first()->getId(),
'participation[status]' => $event->getType()->getStatuses()->first()->getId()
));
'participation[status]' => $event->getType()->getStatuses()->first()->getId(),
]);
$this->assertTrue($this->client->getResponse()->isRedirect());
// reload the event and test there is a new participation
$event = $this->em->getRepository('ChillEventBundle:Event')
->find($event->getId());
->find($event->getId());
$this->em->refresh($event);
$this->assertEquals($nbParticipations + 1, $event->getParticipations()->count(),
"Test we have persisted a new participation associated to the test");
$this->assertEquals(
$nbParticipations + 1,
$event->getParticipations()->count(),
'Test we have persisted a new participation associated to the test'
);
}
public function testEditMultipleAction()
public function testNewSingleAction()
{
/* @var $event \Chill\EventBundle\Entity\Event */
$event = $this->getRandomEventWithMultipleParticipations();
$crawler = $this->client->request('GET', '/fr/event/participation/'.$event->getId().
'/edit_multiple');
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
$button = $crawler->selectButton('Mettre à jour');
$this->assertEquals(1, $button->count(), "test the form with button 'mettre à jour' exists ");
$this->client->submit($button->form(), array(
'form[participations][0][role]' => $event->getType()->getRoles()->first()->getId(),
'form[participations][0][status]' => $event->getType()->getStatuses()->first()->getId(),
'form[participations][1][role]' => $event->getType()->getRoles()->last()->getId(),
'form[participations][1][status]' => $event->getType()->getStatuses()->last()->getId(),
));
$this->assertTrue($this->client->getResponse()
->isRedirect('/fr/event/event/'.$event->getId().'/show'));
$event = $this->getRandomEvent();
// record the number of participation for the event
$nbParticipations = $event->getParticipations()->count();
$person = $this->getRandomPerson();
$crawler = $this->client->request(
'GET',
'/fr/event/participation/new',
[
'person_id' => $person->getId(),
'event_id' => $event->getId(),
]
);
$this->assertEquals(
200,
$this->client->getResponse()->getStatusCode(),
'test that /fr/event/participation/new is successful'
);
$button = $crawler->selectButton('Créer');
$this->assertNotNull($button, "test the form with button 'Créer' exists");
$this->client->submit($button->form(), [
'participation[role]' => $event->getType()->getRoles()->first()->getId(),
'participation[status]' => $event->getType()->getStatuses()->first()->getId(),
]);
$this->assertTrue($this->client->getResponse()->isRedirect());
$crawler = $this->client->followRedirect();
$span = $crawler->filter('table td span.entity-person a:contains("'
. $person->getFirstName() . '"):contains("' . $person->getLastname() . '")');
$this->assertGreaterThan(0, count($span));
// as the container has reloaded, reload the event
$event = $this->em->getRepository('ChillEventBundle:Event')->find($event->getId());
$this->em->refresh($event);
$this->assertEquals($nbParticipations + 1, $event->getParticipations()->count());
}
/**
* @param mixed $centerName
* @param mixed $circleName
*
* @return \Chill\EventBundle\Entity\Event
*/
protected function getRandomEvent($centerName = 'Center A', $circleName = 'social')
{
$center = $this->em->getRepository('ChillMainBundle:Center')
->findByName($centerName);
$circles = $this->em->getRepository('ChillMainBundle:Scope')
->findAll();
array_filter($circles, function ($circle) use ($circleName) {
return in_array($circleName, $circle->getName());
});
$circle = $circles[0];
$events = $this->em->getRepository('ChillEventBundle:Event')
->findBy(['center' => $center, 'circle' => $circle]);
return $events[array_rand($events)];
}
/**
* Return a random event only if he has more than one participation.
*
* @param string $centerName
* @param type $circleName
*
* @return \Chill\EventBundle\Entity\Event
*/
protected function getRandomEventWithMultipleParticipations(
$centerName = 'Center A',
$circleName = 'social'
)
{
$event = $this->getRandomEvent($centerName, $circleName);
return $event->getParticipations()->count() > 1 ?
$event :
$this->getRandomEventWithMultipleParticipations($centerName, $circleName);
}
/**
* Returns a person randomly.
*
* This function does not give the same person twice
* for each test.
*
* You may ask to ignore some people by adding their id to the property
* `$this->personsIdsCache`
*
* @param string $centerName
*
* @return \Chill\PersonBundle\Entity\Person
*/
protected function getRandomPerson($centerName = 'Center A')
{
$center = $this->em->getRepository('ChillMainBundle:Center')
->findByName($centerName);
$persons = $this->em->getRepository('ChillPersonBundle:Person')
->findBy(['center' => $center]);
$person = $persons[array_rand($persons)];
if (in_array($person->getId(), $this->personsIdsCache)) {
return $this->getRandomPerson($centerName); // we try another time
}
$this->personsIdsCache[] = $person->getId();
return $person;
}
}

View File

@@ -1,15 +1,27 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class RoleControllerTest extends WebTestCase
{
public function testSkipped()
{
$this->markTestSkipped();
}
/*
public function testCompleteScenario()
{
@@ -55,5 +67,5 @@ class RoleControllerTest extends WebTestCase
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
*/
}

View File

@@ -1,15 +1,27 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
* @coversNothing
*/
class StatusControllerTest extends WebTestCase
{
public function testSkipped()
{
$this->markTestSkipped();
}
/*
public function testCompleteScenario()
{
@@ -55,5 +67,5 @@ class StatusControllerTest extends WebTestCase
$this->assertNotRegExp('/Foo/', $client->getResponse()->getContent());
}
*/
*/
}

View File

@@ -1,398 +1,385 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Tests\Search;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Chill\EventBundle\Entity\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Chill\EventBundle\Search\EventSearch;
use DateTime;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Test the EventSearch class
* Test the EventSearch class.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @internal
* @coversNothing
*/
class EventSearchTest extends WebTestCase
{
/**
* The eventSearch service, which is used to search events
* The center A.
*
* @var \Chill\MainBundle\Entity\Center
*/
protected $centerA;
/**
* @var \Symfony\Component\BrowserKit\Client
*/
protected $client;
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
protected $entityManager;
/**
* Events created during this test.
*
* @var Event[]
*/
protected $events = [];
/**
* The eventSearch service, which is used to search events.
*
* @var \Chill\EventBundle\Search\EventSearch
*/
protected $eventSearch;
/**
*
* @var \Doctrine\ORM\EntityManagerInterface
*/
protected $entityManager;
/**
* The center A
*
* @var \Chill\MainBundle\Entity\Center
*/
protected $centerA;
/**
* a random event type
* a random event type.
*
* @var \Chill\EventBundle\Entity\EventType
*/
protected $eventType;
/**
* Events created during this test
*
* @var Event[]
*/
protected $events = array();
/**
*
* @var \Prophecy\Prophet
*/
protected $prophet;
/**
*
* @var \Symfony\Component\BrowserKit\Client
*/
protected $client;
public function setUp()
{
self::bootKernel();
/* @var $kernel \Symfony\Component\HttpKernel\KernelInterface */
$kernel = self::$kernel;
$this->client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR'
));
$this->prophet = new \Prophecy\Prophet;
$this->client = static::createClient([], [
'PHP_AUTH_USER' => 'center a_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR',
]);
$this->prophet = new \Prophecy\Prophet();
$this->entityManager = self::$kernel->getContainer()
->get('doctrine.orm.entity_manager')
;
->get('doctrine.orm.entity_manager');
$this->centerA = $this->entityManager
->getRepository('ChillMainBundle:Center')
->findOneBy(array('name' => 'Center A'));
->getRepository('ChillMainBundle:Center')
->findOneBy(['name' => 'Center A']);
$this->eventType = $this->entityManager
->getRepository('ChillEventBundle:EventType')
->findAll()[0];
->getRepository('ChillEventBundle:EventType')
->findAll()[0];
$this->createEvents();
}
public function tearDown()
{
foreach ($this->events as $event) {
$this->entityManager->createQuery('DELETE FROM ChillEventBundle:Event e WHERE e.id = :event_id')
->setParameter('event_id', $event->getId())
->execute();
->setParameter('event_id', $event->getId())
->execute();
}
$this->events = array();
$this->events = [];
}
public function testDisplayAll()
{
$crawler = $this->client->request('GET', '/fr/search', [
'q' => '@events',
]);
$this->assertGreaterThanOrEqual(
2,
$crawler->filter('table.events tr')->count(),
'assert than more than 2 tr are present'
);
}
/**
* Test that a user connected with an user with the wrong center does not
* see the events.
*/
public function testDisplayAllWrongUser()
{
$client = static::createClient([], [
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR',
]);
$crawler = $client->request('GET', '/fr/search', [
'q' => '@events printemps',
]);
$this->assertEquals(
0,
$crawler->filter('tr:contains("Printemps")')->count(),
'assert that the word "printemps" is present'
);
}
public function testSearchByDateDateBetween()
{
// serach with date from **and** date-to
$crawler = $this->client->request('GET', '/fr/search', [
'q' => '@events date-from:2016-05-30 date-to:2016-06-20',
]);
/* @var $dateFrom \DateTime the date from in DateTime */
$dateFrom = DateTime::createFromFormat('Y-m-d', '2016-05-30');
$dateTo = DateTime::createFromFormat('Y-m-d', '2016-06-20');
$dates = $this->iterateOnRowsToFindDate($crawler->filter('tr'));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
$this->assertLessThanOrEqual($dateTo, $date);
}
// there should not have any other results, but if any other bundle
// add some other event, we go on next pages
if ($crawler->selectLink('Voir tous les résultats')->count() == 0) {
return;
}
// click on link "Voir tous les résultats"
$crawlerAllResults = $this->client->click($crawler
->selectLink('Voir tous les résultats')->link());
$dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter('tr'));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
$this->assertLessThanOrEqual($dateTo, $date);
}
//iterate on pagination
$crawlerAllResults->filter('.pagination a')->each(function ($a, $i) use ($dateFrom) {
$page = $this->client->click($a->link());
$dates = $this->iterateOnRowsToFindDate($page->filter('tr'));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
$this->assertLessThanOrEqual($dateTo, $date);
}
});
}
public function testSearchByDateDateFromOnly()
{
// search with date from
$crawler = $this->client->request('GET', '/fr/search', [
'q' => '@events date-from:2016-05-30',
]);
/* @var $dateFrom \DateTime the date from in DateTime */
$dateFrom = DateTime::createFromFormat('Y-m-d', '2016-05-30');
$dates = $this->iterateOnRowsToFindDate($crawler->filter('tr'));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
}
// click on link "Voir tous les résultats"
$crawlerAllResults = $this->client->click($crawler
->selectLink('Voir tous les résultats')->link());
$dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter('tr'));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
}
//iterate on pagination
$crawlerAllResults->filter('.pagination a')->each(function ($a, $i) use ($dateFrom) {
$page = $this->client->click($a->link());
$dates = $this->iterateOnRowsToFindDate($page->filter('tr'));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
}
});
}
public function testSearchByDateDateTo()
{
// serach with date from **and** date-to
$crawler = $this->client->request('GET', '/fr/search', [
'q' => '@events date:2016-05-30',
]);
/* @var $dateFrom \DateTime the date from in DateTime */
$dateTo = DateTime::createFromFormat('Y-m-d', '2016-05-30');
$dates = $this->iterateOnRowsToFindDate($crawler->filter('tr'));
foreach ($dates as $date) {
$this->assertLessThanOrEqual($dateTo, $date);
}
if ($crawler->selectLink('Voir tous les résultats')->count() == 0) {
return;
}
// click on link "Voir tous les résultats"
$crawlerAllResults = $this->client->click($crawler
->selectLink('Voir tous les résultats')->link());
$dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter('tr'));
foreach ($dates as $date) {
$this->assertLessThanOrEqual($dateTo, $date);
}
//iterate on pagination
$crawlerAllResults->filter('.pagination a')->each(function ($a, $i) {
$page = $this->client->click($a->link());
$dates = $this->iterateOnRowsToFindDate($page->filter('tr'));
foreach ($dates as $date) {
$this->assertLessThanOrEqual($dateTo, $date);
}
});
}
public function testSearchByDefault()
{
$crawler = $this->client->request('GET', '/fr/search', [
'q' => '@events printemps',
]);
$this->assertEquals(
1,
$crawler->filter('table.events tr')->count() - 1 /* as the header is a th */ ,
'assert than more than 2 tr are present'
);
$this->assertEquals(
1,
$crawler->filter('tr:contains("Printemps")')->count(),
'assert that the word "printemps" is present'
);
}
public function testSearchByName()
{
$crawler = $this->client->request('GET', '/fr/search', [
'q' => '@events name:printemps',
]);
$this->assertEquals(
1,
$crawler->filter('table.events tr')->count() - 1 /* as the header is a th */ ,
'assert than more than 2 tr are present'
);
$this->assertEquals(
1,
$crawler->filter('tr:contains("Printemps")')->count(),
'assert that the word "printemps" is present'
);
}
protected function createEvents()
{
$event1 = (new Event())
->setCenter($this->centerA)
->setDate(new \DateTime('2016-05-30'))
->setName('Printemps européen')
->setType($this->eventType)
->setCircle($this->getCircle())
;
->setCenter($this->centerA)
->setDate(new DateTime('2016-05-30'))
->setName('Printemps européen')
->setType($this->eventType)
->setCircle($this->getCircle());
$this->entityManager->persist($event1);
$this->events[] = $event1;
$event2 = (new Event())
->setCenter($this->centerA)
->setDate(new \DateTime('2016-06-24'))
->setName('Hiver de la droite')
->setType($this->eventType)
->setCircle($this->getCircle())
;
->setCenter($this->centerA)
->setDate(new DateTime('2016-06-24'))
->setName('Hiver de la droite')
->setType($this->eventType)
->setCircle($this->getCircle());
$this->entityManager->persist($event2);
$this->events[] = $event2;
$this->entityManager->flush();
}
/**
*
* @param string $name the name of the circle
*
* @return \Chill\MainBundle\Entity\Scope
*/
protected function getCircle($name = 'social')
{
$circles = $this->entityManager->getRepository('ChillMainBundle:Scope')
->findAll();
->findAll();
/* @var $circle \Chill\MainBundle\Entity\Scope */
foreach($circles as $circle) {
foreach ($circles as $circle) {
if (in_array($name, $circle->getName())) {
return $circle;
}
}
}
public function testDisplayAll()
{
$crawler = $this->client->request('GET', '/fr/search', array(
'q' => '@events'
));
$this->assertGreaterThanOrEqual(2, $crawler->filter('table.events tr')->count(),
'assert than more than 2 tr are present');
}
public function testSearchByDefault()
{
$crawler = $this->client->request('GET', '/fr/search', array(
'q' => '@events printemps'
));
$this->assertEquals(
1,
$crawler->filter('table.events tr')->count() - 1 /* as the header is a th */,
'assert than more than 2 tr are present');
$this->assertEquals(
1,
$crawler->filter('tr:contains("Printemps")')->count(),
'assert that the word "printemps" is present');
}
public function testSearchByName()
{
$crawler = $this->client->request('GET', '/fr/search', array(
'q' => '@events name:printemps'
));
$this->assertEquals(
1,
$crawler->filter('table.events tr')->count() - 1 /* as the header is a th */,
'assert than more than 2 tr are present');
$this->assertEquals(
1,
$crawler->filter('tr:contains("Printemps")')->count(),
'assert that the word "printemps" is present');
}
public function testSearchByDateDateFromOnly()
{
// search with date from
$crawler = $this->client->request('GET', '/fr/search', array(
'q' => '@events date-from:2016-05-30'
));
/* @var $dateFrom \DateTime the date from in DateTime */
$dateFrom = \DateTime::createFromFormat("Y-m-d", "2016-05-30");
$dates = $this->iterateOnRowsToFindDate($crawler->filter("tr"));
foreach($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
}
// click on link "Voir tous les résultats"
$crawlerAllResults = $this->client->click($crawler
->selectLink("Voir tous les résultats")->link());
$dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter("tr"));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
}
//iterate on pagination
$crawlerAllResults->filter(".pagination a")->each(function($a, $i) use ($dateFrom) {
$page = $this->client->click($a->link());
$dates = $this->iterateOnRowsToFindDate($page->filter("tr"));
foreach($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
}
});
}
public function testSearchByDateDateBetween()
{
// serach with date from **and** date-to
$crawler = $this->client->request('GET', '/fr/search', array(
'q' => '@events date-from:2016-05-30 date-to:2016-06-20'
));
/* @var $dateFrom \DateTime the date from in DateTime */
$dateFrom = \DateTime::createFromFormat("Y-m-d", "2016-05-30");
$dateTo = \DateTime::createFromFormat("Y-m-d", "2016-06-20");
$dates = $this->iterateOnRowsToFindDate($crawler->filter("tr"));
foreach($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
$this->assertLessThanOrEqual($dateTo, $date);
}
// there should not have any other results, but if any other bundle
// add some other event, we go on next pages
if ($crawler->selectLink("Voir tous les résultats")->count() == 0) {
return ;
}
// click on link "Voir tous les résultats"
$crawlerAllResults = $this->client->click($crawler
->selectLink("Voir tous les résultats")->link());
$dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter("tr"));
foreach ($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
$this->assertLessThanOrEqual($dateTo, $date);
}
//iterate on pagination
$crawlerAllResults->filter(".pagination a")->each(function($a, $i) use ($dateFrom) {
$page = $this->client->click($a->link());
$dates = $this->iterateOnRowsToFindDate($page->filter("tr"));
foreach($dates as $date) {
$this->assertGreaterThanOrEqual($dateFrom, $date);
$this->assertLessThanOrEqual($dateTo, $date);
}
});
}
public function testSearchByDateDateTo()
{
// serach with date from **and** date-to
$crawler = $this->client->request('GET', '/fr/search', array(
'q' => '@events date:2016-05-30'
));
/* @var $dateFrom \DateTime the date from in DateTime */
$dateTo = \DateTime::createFromFormat("Y-m-d", "2016-05-30");
$dates = $this->iterateOnRowsToFindDate($crawler->filter("tr"));
foreach($dates as $date) {
$this->assertLessThanOrEqual($dateTo, $date);
}
if ($crawler->selectLink("Voir tous les résultats")->count() == 0) {
return ;
}
// click on link "Voir tous les résultats"
$crawlerAllResults = $this->client->click($crawler
->selectLink("Voir tous les résultats")->link());
$dates = $this->iterateOnRowsToFindDate($crawlerAllResults->filter("tr"));
foreach ($dates as $date) {
$this->assertLessThanOrEqual($dateTo, $date);
}
//iterate on pagination
$crawlerAllResults->filter(".pagination a")->each(function($a, $i) use ($dateFrom) {
$page = $this->client->click($a->link());
$dates = $this->iterateOnRowsToFindDate($page->filter("tr"));
foreach($dates as $date) {
$this->assertLessThanOrEqual($dateTo, $date);
}
});
}
/**
* this function iterate on row from results of events and return the content
* of the second column (which should contains the date) in DateTime objects
*
* @param \Symfony\Component\DomCrawler\Crawler $trs
* @return \DateTime[]
* of the second column (which should contains the date) in DateTime objects.
*
* @return DateTime[]
*/
private function iterateOnRowsToFindDate(\Symfony\Component\DomCrawler\Crawler $trs)
{
$months = array(
"janvier" => 1,
"février" => 2,
"mars" => 3,
"avril" => 4,
"mai" => 5,
"juin" => 6,
"juillet" => 7,
"août" => 8,
"septembre" => 9,
"octobre" => 10,
"novembre" => 11,
"décembre" => 12
);
$results = $trs->each(function($tr, $i) use ($months) {
$months = [
'janvier' => 1,
'février' => 2,
'mars' => 3,
'avril' => 4,
'mai' => 5,
'juin' => 6,
'juillet' => 7,
'août' => 8,
'septembre' => 9,
'octobre' => 10,
'novembre' => 11,
'décembre' => 12,
];
$results = $trs->each(function ($tr, $i) use ($months) {
// we skip the first row
if ($i > 0) {
if (0 < $i) {
// get the second node, which should contains a date
$tdDate = $tr->filter("td")->eq(1);
$tdDate = $tr->filter('td')->eq(1);
// transform the date, which should be in french, into a DateTime object
$parts = explode(" ", $tdDate->text());
return \DateTime::createFromFormat("Y-m-d", $parts[2].
"-".$months[$parts[1]]."-".$parts[0]);
$parts = explode(' ', $tdDate->text());
return DateTime::createFromFormat('Y-m-d', $parts[2] .
'-' . $months[$parts[1]] . '-' . $parts[0]);
}
});
// remove the first row
unset($results[0]);
return $results;
}
/**
* Test that a user connected with an user with the wrong center does not
* see the events
*/
public function testDisplayAllWrongUser()
{
$client = static::createClient(array(), array(
'PHP_AUTH_USER' => 'center b_social',
'PHP_AUTH_PW' => 'password',
'HTTP_ACCEPT_LANGUAGE' => 'fr_FR'
));
$crawler = $client->request('GET', '/fr/search', array(
'q' => '@events printemps'
));
$this->assertEquals(0, $crawler->filter('tr:contains("Printemps")')->count(),
'assert that the word "printemps" is present');
}
}

View File

@@ -1,42 +1,30 @@
<?php
/*
/**
* Chill is a software for social workers
* Copyright (C) 2019 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/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\EventBundle\Timeline;
use Chill\EventBundle\Entity\Event;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Timeline\TimelineProviderInterface;
use Chill\MainBundle\Timeline\TimelineSingleQuery;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\EntityManager;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Doctrine\ORM\Mapping\ClassMetadata;
use LogicException;
use RuntimeException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role;
use Doctrine\ORM\Mapping\ClassMetadata;
use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\User;
/**
* Class TimelineEventProvider
*
* @package Chill\EventBundle\Timeline
* @author Mathieu Jaumotte jaum_mathieu@collectifs.net
* Class TimelineEventProvider.
*/
class TimelineEventProvider implements TimelineProviderInterface
{
@@ -44,23 +32,19 @@ class TimelineEventProvider implements TimelineProviderInterface
* @var EntityManager
*/
protected $em;
/**
* @var AuthorizationHelper
*/
protected $helper;
/**
* @var User
*/
protected $user;
/**
* TimelineEventProvider constructor.
*
* @param EntityManager $em
* @param AuthorizationHelper $helper
* @param TokenStorageInterface $storage
*/
public function __construct(
EntityManager $em,
@@ -69,44 +53,104 @@ class TimelineEventProvider implements TimelineProviderInterface
) {
$this->em = $em;
$this->helper = $helper;
if (!$storage->getToken()->getUser() instanceof User) {
throw new \RuntimeException('A user should be authenticated !');
throw new RuntimeException('A user should be authenticated !');
}
$this->user = $storage->getToken()->getUser();
}
/**
* @param string $context
* @param array $args
* @return array|string[]
*
* @throws \Doctrine\ORM\Mapping\MappingException
*
* @return array|string[]
*/
public function fetchQuery($context, array $args)
{
$this->checkContext($context);
$metadataEvent = $this->em->getClassMetadata('ChillEventBundle:Event');
$metadataParticipation = $this->em->getClassMetadata('ChillEventBundle:Participation');
$metadataPerson = $this->em->getClassMetadata('ChillPersonBundle:Person');
$query = TimelineSingleQuery::fromArray([
'id' => $metadataEvent->getTableName().'.'.$metadataEvent->getColumnName('id'),
return TimelineSingleQuery::fromArray([
'id' => $metadataEvent->getTableName() . '.' . $metadataEvent->getColumnName('id'),
'type' => 'event',
'date' => $metadataEvent->getTableName().'.'.$metadataEvent->getColumnName('date'),
'date' => $metadataEvent->getTableName() . '.' . $metadataEvent->getColumnName('date'),
'FROM' => $this->getFromClause($metadataEvent, $metadataParticipation, $metadataPerson),
'WHERE' => $this->getWhereClause($metadataEvent, $metadataParticipation, $metadataPerson, $args['person']),
'parameters' => []
'parameters' => [],
]);
return $query;
}
/**
* @return array|mixed[]
*/
public function getEntities(array $ids)
{
$events = $this->em->getRepository(Event::class)
->findBy(['id' => $ids]);
$result = [];
foreach ($events as $event) {
$result[$event->getId()] = $event;
}
return $result;
}
/**
* @param Event $entity
* @param string $context
*
* @return array|mixed[]
*/
public function getEntityTemplate($entity, $context, array $args)
{
$this->checkContext($context);
return [
'template' => 'ChillEventBundle:Timeline:event_person_context.html.twig',
'template_data' => [
'event' => $entity,
'person' => $args['person'],
'user' => $this->user,
],
];
}
/**
* @param string $type
*
* @return bool
*/
public function supportsType($type)
{
return 'event' === $type;
}
/**
* check if the context is supported.
*
* @param string $context
*
* @throws LogicException if the context is not supported
*/
private function checkContext($context)
{
if ('person' !== $context) {
throw new LogicException("The context '{$context}' is not "
. "supported. Currently only 'person' is supported");
}
}
/**
* @param ClassMetadata $metadataEvent
* @param ClassMetadata $metadataParticipation
* @param ClassMetadata $metadataPerson
* @return string
* @throws \Doctrine\ORM\Mapping\MappingException
*
* @return string
*/
private function getFromClause(
ClassMetadata $metadataEvent,
@@ -115,30 +159,25 @@ class TimelineEventProvider implements TimelineProviderInterface
) {
$eventParticipationMapping = $metadataParticipation->getAssociationMapping('event');
$participationPersonMapping = $metadataParticipation->getAssociationMapping('person');
return $metadataEvent->getTableName()
. ' JOIN ' . $metadataParticipation->getTableName()
. ' ON ' . $metadataParticipation->getTableName()
. '.' . $eventParticipationMapping['joinColumns'][0]['name']
. ' = ' . $metadataEvent->getTableName()
. '.' . $eventParticipationMapping['joinColumns'][0]['referencedColumnName']
.' JOIN '.$metadataParticipation->getTableName()
.' ON ' .$metadataParticipation->getTableName()
.'.' .$eventParticipationMapping['joinColumns'][0]['name']
.' = ' .$metadataEvent->getTableName()
.'.' .$eventParticipationMapping['joinColumns'][0]['referencedColumnName']
.' JOIN '.$metadataPerson->getTableName()
.' ON ' .$metadataPerson->getTableName()
.'.' .$participationPersonMapping['joinColumns'][0]['referencedColumnName']
.' = ' .$metadataParticipation->getTableName()
.'.' .$participationPersonMapping['joinColumns'][0]['name']
;
. ' JOIN ' . $metadataPerson->getTableName()
. ' ON ' . $metadataPerson->getTableName()
. '.' . $participationPersonMapping['joinColumns'][0]['referencedColumnName']
. ' = ' . $metadataParticipation->getTableName()
. '.' . $participationPersonMapping['joinColumns'][0]['name'];
}
/**
* @param ClassMetadata $metadataEvent
* @param ClassMetadata $metadataParticipation
* @param ClassMetadata $metadataPerson
* @param Person $person
* @return string
* @throws \Doctrine\ORM\Mapping\MappingException
*
* @return string
*/
private function getWhereClause(
ClassMetadata $metadataEvent,
@@ -147,20 +186,23 @@ class TimelineEventProvider implements TimelineProviderInterface
Person $person
) {
$role = new Role('CHILL_EVENT_SEE');
$reachableCenters = $this->helper->getReachableCenters($this->user, $role);
$associationMapping = $metadataParticipation->getAssociationMapping('person');
if (count($reachableCenters) === 0) {
return 'FALSE = TRUE';
}
$whereClause = sprintf( '%s = %d',
$whereClause = sprintf(
'%s = %d',
$associationMapping['joinColumns'][0]['name'],
$person->getId());
$person->getId()
);
// and
$centerAndScopeLines = array();
$centerAndScopeLines = [];
foreach ($reachableCenters as $center) {
$reachableCircleId = array_map(
function (Scope $scope) { return $scope->getId(); },
@@ -176,68 +218,8 @@ class TimelineEventProvider implements TimelineProviderInterface
implode(',', $reachableCircleId)
);
}
$whereClause .= ' AND ('. implode(' OR ', $centerAndScopeLines) .')';
$whereClause .= ' AND (' . implode(' OR ', $centerAndScopeLines) . ')';
return $whereClause;
}
/**
* check if the context is supported
*
* @param string $context
* @throws \LogicException if the context is not supported
*/
private function checkContext($context)
{
if ($context !== 'person') {
throw new \LogicException("The context '$context' is not "
. "supported. Currently only 'person' is supported");
}
}
/**
* @param string $type
* @return bool
*/
public function supportsType($type)
{
return $type === 'event';
}
/**
* @param array $ids
* @return array|mixed[]
*/
public function getEntities(array $ids) {
$events = $this->em->getRepository(Event::class)
->findBy(array('id' => $ids));
$result = array();
foreach ($events as $event) {
$result[$event->getId()] = $event;
}
return $result;
}
/**
* @param Event $entity
* @param string $context
* @param array $args
* @return array|mixed[]
*/
public function getEntityTemplate($entity, $context, array $args) {
$this->checkContext($context);
return array(
'template' => 'ChillEventBundle:Timeline:event_person_context.html.twig',
'template_data' => array(
'event' => $entity,
'person' => $args['person'],
'user' => $this->user
)
);
}
}

View File

@@ -1,18 +1,51 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\Migrations\Event;
use Doctrine\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Initialize the bundle chill_event
* Initialize the bundle chill_event.
*/
class Version20160318111334 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_role DROP CONSTRAINT FK_AA714E54C54C8C93');
$this->addSql('ALTER TABLE chill_event_status DROP CONSTRAINT FK_A6CC85D0C54C8C93');
$this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768ACD60322AC');
$this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768AC6BF700BD');
$this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768AC71F7E88B');
// drop center_id constraint
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC85932F377');
// drop type_id constraint
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC8C54C8C93');
// drop circle_id constraint
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC870EE2FF6');
$this->addSql('DROP SEQUENCE chill_event_event_type_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_role_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_status_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_event_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_participation_id_seq CASCADE');
$this->addSql('DROP TABLE chill_event_event_type');
$this->addSql('DROP TABLE chill_event_role');
$this->addSql('DROP TABLE chill_event_status');
$this->addSql('DROP TABLE chill_event_event');
$this->addSql('DROP TABLE chill_event_participation');
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
@@ -62,7 +95,7 @@ class Version20160318111334 extends AbstractMigration
$this->addSql('CREATE INDEX IDX_FA320FC85932F377 ON chill_event_event (center_id)');
$this->addSql('CREATE INDEX IDX_FA320FC8C54C8C93 ON chill_event_event (type_id)');
$this->addSql('CREATE INDEX IDX_FA320FC870EE2FF6 ON chill_event_event (circle_id)');
$this->addSql('ALTER TABLE chill_event_event '
. 'ADD CONSTRAINT FK_FA320FC85932F377 FOREIGN KEY (center_id) '
. 'REFERENCES centers (id) '
@@ -103,39 +136,5 @@ class Version20160318111334 extends AbstractMigration
. 'FOREIGN KEY (status_id) '
. 'REFERENCES chill_event_status (id) '
. 'NOT DEFERRABLE INITIALLY IMMEDIATE');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_role DROP CONSTRAINT FK_AA714E54C54C8C93');
$this->addSql('ALTER TABLE chill_event_status DROP CONSTRAINT FK_A6CC85D0C54C8C93');
$this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768ACD60322AC');
$this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768AC6BF700BD');
$this->addSql('ALTER TABLE chill_event_participation DROP CONSTRAINT FK_4E7768AC71F7E88B');
// drop center_id constraint
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC85932F377');
// drop type_id constraint
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC8C54C8C93');
// drop circle_id constraint
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC870EE2FF6');
$this->addSql('DROP SEQUENCE chill_event_event_type_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_role_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_status_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_event_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chill_event_participation_id_seq CASCADE');
$this->addSql('DROP TABLE chill_event_event_type');
$this->addSql('DROP TABLE chill_event_role');
$this->addSql('DROP TABLE chill_event_status');
$this->addSql('DROP TABLE chill_event_event');
$this->addSql('DROP TABLE chill_event_participation');
}
}

View File

@@ -1,4 +1,13 @@
<?php declare(strict_types=1);
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\Migrations\Event;
@@ -6,24 +15,23 @@ use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Switch event date to datetime
* Switch event date to datetime.
*/
final class Version20190110140538 extends AbstractMigration
{
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_event ALTER date TYPE TIMESTAMP(0) WITHOUT TIME ZONE');
$this->addSql('ALTER TABLE chill_event_event ALTER date DROP DEFAULT');
}
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_event ALTER date TYPE DATE');
$this->addSql('ALTER TABLE chill_event_event ALTER date DROP DEFAULT');
}
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_event ALTER date TYPE TIMESTAMP(0) WITHOUT TIME ZONE');
$this->addSql('ALTER TABLE chill_event_event ALTER date DROP DEFAULT');
}
}

View File

@@ -1,4 +1,13 @@
<?php declare(strict_types=1);
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\Migrations\Event;
@@ -6,20 +15,10 @@ use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Add a moderator field
* Add a moderator field.
*/
final class Version20190115140042 extends AbstractMigration
{
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_event ADD moderator_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT FK_FA320FC8D0AFA354 FOREIGN KEY (moderator_id) REFERENCES chill_person_person (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('CREATE INDEX IDX_FA320FC8D0AFA354 ON chill_event_event (moderator_id)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
@@ -29,4 +28,14 @@ final class Version20190115140042 extends AbstractMigration
$this->addSql('DROP INDEX IDX_FA320FC8D0AFA354');
$this->addSql('ALTER TABLE chill_event_event DROP moderator_id');
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_event ADD moderator_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT FK_FA320FC8D0AFA354 FOREIGN KEY (moderator_id) REFERENCES chill_person_person (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('CREATE INDEX IDX_FA320FC8D0AFA354 ON chill_event_event (moderator_id)');
}
}

View File

@@ -1,4 +1,13 @@
<?php declare(strict_types=1);
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\Migrations\Event;
@@ -6,10 +15,19 @@ use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Moderator, relation with User (not Person)
* Moderator, relation with User (not Person).
*/
final class Version20190201143121 extends AbstractMigration
{
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT fk_fa320fc8d0afa354');
$this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT fk_fa320fc8d0afa354 FOREIGN KEY (moderator_id) REFERENCES chill_person_person (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
@@ -18,14 +36,4 @@ final class Version20190201143121 extends AbstractMigration
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT FK_FA320FC8D0AFA354');
$this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT FK_FA320FC8D0AFA354 FOREIGN KEY (moderator_id) REFERENCES users (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_event_event DROP CONSTRAINT fk_fa320fc8d0afa354');
$this->addSql('ALTER TABLE chill_event_event ADD CONSTRAINT fk_fa320fc8d0afa354 FOREIGN KEY (moderator_id) REFERENCES chill_person_person (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
}