fix: SA: Fix "might not be defined" rule.

SA stands for Static Analysis.
This commit is contained in:
Pol Dellaiera 2021-11-16 11:41:12 +01:00
parent a7b96f1756
commit f8aeb08594
No known key found for this signature in database
GPG Key ID: D476DFE9C67467CA
14 changed files with 365 additions and 620 deletions

View File

@ -1,15 +1,5 @@
parameters:
ignoreErrors:
-
message: "#^Variable \\$activities might not be defined\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Controller/ActivityController.php
-
message: "#^Variable \\$view might not be defined\\.$#"
count: 4
path: src/Bundle/ChillActivityBundle/Controller/ActivityController.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
@ -50,16 +40,6 @@ parameters:
count: 1
path: src/Bundle/ChillActivityBundle/Export/Export/StatActivityDuration.php
-
message: "#^Variable \\$header might not be defined\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Export/Export/StatActivityDuration.php
-
message: "#^Variable \\$select might not be defined\\.$#"
count: 1
path: src/Bundle/ChillActivityBundle/Export/Export/StatActivityDuration.php
-
message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1
@ -155,11 +135,6 @@ parameters:
count: 2
path: src/Bundle/ChillBudgetBundle/Security/Authorization/BudgetElementVoter.php
-
message: "#^Variable \\$view might not be defined\\.$#"
count: 4
path: src/Bundle/ChillCalendarBundle/Controller/CalendarController.php
-
message: "#^Access to an undefined property Chill\\\\CalendarBundle\\\\DataFixtures\\\\ORM\\\\LoadCalendarRange\\:\\:\\$userRepository\\.$#"
count: 2
@ -260,11 +235,6 @@ parameters:
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Form/CustomFieldType.php
-
message: "#^Variable \\$optionBuilder might not be defined\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Form/CustomFieldsGroupType.php
-
message: "#^Call to sprintf contains 0 placeholders, 1 value given\\.$#"
count: 1
@ -535,11 +505,6 @@ parameters:
count: 1
path: src/Bundle/ChillMainBundle/Command/LoadPostalCodesCommand.php
-
message: "#^Variable \\$csv might not be defined\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Command/LoadPostalCodesCommand.php
-
message: "#^Method Chill\\\\MainBundle\\\\Command\\\\SetPasswordCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1
@ -620,11 +585,6 @@ parameters:
count: 1
path: src/Bundle/ChillMainBundle/DependencyInjection/Widget/AbstractWidgetsCompilerPass.php
-
message: "#^Variable \\$p might not be defined\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Doctrine/DQL/OverlapsI.php
-
message: "#^Method Chill\\\\MainBundle\\\\Doctrine\\\\Type\\\\PointType\\:\\:getSqlDeclaration\\(\\) does not match parent method name\\: Doctrine\\\\DBAL\\\\Types\\\\Type\\:\\:getSQLDeclaration\\(\\)\\.$#"
count: 1
@ -661,23 +621,8 @@ parameters:
path: src/Bundle/ChillMainBundle/Export/ExportManager.php
-
message: "#^Function findColumnPosition not found\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Export/Formatter/CSVFormatter.php
-
message: "#^Inner named functions are not supported by PHPStan\\. Consider refactoring to an anonymous function, class method, or a top\\-level\\-defined function\\. See issue \\#165 \\(https\\://github\\.com/phpstan/phpstan/issues/165\\) for more details\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Export/Formatter/CSVFormatter.php
-
message: "#^Method Chill\\\\MainBundle\\\\Export\\\\Formatter\\\\CSVFormatter\\:\\:orderingHeaders\\(\\) should return Chill\\\\MainBundle\\\\Export\\\\Formatter\\\\type but return statement is missing\\.$#"
count: 1
path: src/Bundle/ChillMainBundle/Export/Formatter/CSVFormatter.php
-
message: "#^Variable \\$line might not be defined\\.$#"
count: 1
message: "#^Foreach overwrites \\$line with its value variable\\.$#"
count: 2
path: src/Bundle/ChillMainBundle/Export/Formatter/CSVFormatter.php
-
@ -940,16 +885,6 @@ parameters:
count: 6
path: src/Bundle/ChillPersonBundle/Command/ImportPeopleFromCSVCommand.php
-
message: "#^Variable \\$headers might not be defined\\.$#"
count: 2
path: src/Bundle/ChillPersonBundle/Command/ImportPeopleFromCSVCommand.php
-
message: "#^Variable \\$rawHeaders might not be defined\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Command/ImportPeopleFromCSVCommand.php
-
message: "#^Variable \\$street1Value might not be defined\\.$#"
count: 1
@ -1255,11 +1190,6 @@ parameters:
count: 2
path: src/Bundle/ChillPersonBundle/Serializer/Normalizer/PersonNormalizer.php
-
message: "#^Variable \\$entity might not be defined\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Service/Import/SocialWorkMetadata.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2
@ -1370,11 +1300,6 @@ parameters:
count: 4
path: src/Bundle/ChillReportBundle/Timeline/TimelineReportProvider.php
-
message: "#^Variable \\$course might not be defined\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/Controller/SingleTaskController.php
-
message: "#^Undefined variable\\: \\$type$#"
count: 1
@ -1400,16 +1325,6 @@ parameters:
count: 2
path: src/Bundle/ChillTaskBundle/Form/SingleTaskListType.php
-
message: "#^Variable \\$center might not be defined\\.$#"
count: 2
path: src/Bundle/ChillTaskBundle/Form/SingleTaskType.php
-
message: "#^Variable \\$isScopeConcerned might not be defined\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/Form/SingleTaskType.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1

View File

@ -1,28 +1,9 @@
<?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/>.
*/
declare(strict_types=1);
namespace Chill\ActivityBundle\Controller;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepository;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepositoryInterface;
use Chill\ActivityBundle\Security\Authorization\ActivityVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
@ -42,12 +23,7 @@ use Chill\ActivityBundle\Form\ActivityType;
use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Class ActivityController
*
* @package Chill\ActivityBundle\Controller
*/
class ActivityController extends AbstractController
final class ActivityController extends AbstractController
{
protected EventDispatcherInterface $eventDispatcher;
@ -78,8 +54,8 @@ class ActivityController extends AbstractController
*/
public function listAction(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$view = null;
$activities = [];
// TODO: add pagination
[$person, $accompanyingPeriod] = $this->getEntity($request);
@ -105,11 +81,14 @@ class ActivityController extends AbstractController
$view = 'ChillActivityBundle:Activity:listAccompanyingCourse.html.twig';
}
return $this->render($view, array(
'activities' => $activities,
'person' => $person,
'accompanyingCourse' => $accompanyingPeriod,
));
return $this->render(
$view,
[
'activities' => $activities,
'person' => $person,
'accompanyingCourse' => $accompanyingPeriod,
]
);
}
public function selectTypeAction(Request $request): Response
@ -160,6 +139,7 @@ class ActivityController extends AbstractController
public function newAction(Request $request): Response
{
$view = null;
$em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request);
@ -246,7 +226,7 @@ class ActivityController extends AbstractController
$location = $em->getRepository(\Chill\MainBundle\Entity\Location::class)->find($activityData['location']);
$entity->setLocation($location);
}
if (array_key_exists('comment', $activityData)) {
$comment = new CommentEmbeddable();
$comment->setComment($activityData['comment']);
@ -297,6 +277,7 @@ class ActivityController extends AbstractController
public function showAction(Request $request, $id): Response
{
$view = null;
$em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request);
@ -351,6 +332,7 @@ class ActivityController extends AbstractController
*/
public function editAction($id, Request $request): Response
{
$view = null;
$em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request);
@ -422,6 +404,7 @@ class ActivityController extends AbstractController
*/
public function deleteAction(Request $request, $id)
{
$view = null;
$em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request);

View File

@ -1,21 +1,6 @@
<?php
/*
* 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/>.
*/
declare(strict_types=1);
namespace Chill\ActivityBundle\Export\Export;
@ -28,62 +13,47 @@ use Doctrine\ORM\EntityManagerInterface;
/**
* This export allow to compute stats on activity duration.
*
*
* The desired stat must be given in constructor.
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class StatActivityDuration implements ExportInterface
{
/**
*
* @var EntityManagerInterface
*/
protected $entityManager;
const SUM = 'sum';
protected EntityManagerInterface $entityManager;
public const SUM = 'sum';
/**
* The action for this report.
*
* @var string
*/
protected $action;
protected string $action;
/**
* constructor
*
* @param EntityManagerInterface $em
* @param string $action the stat to perform
*/
public function __construct(
EntityManagerInterface $em,
$action = 'sum'
)
public function __construct(EntityManagerInterface $em, string $action = 'sum')
{
$this->entityManager = $em;
$this->action = $action;
}
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder)
{
}
public function getDescription()
{
if ($this->action === self::SUM) {
return "Sum activities duration by various parameters.";
return 'Sum activities duration by various parameters.';
}
}
public function getTitle()
{
if ($this->action === self::SUM) {
return "Sum activity duration";
return 'Sum activity duration';
}
}
public function getType()
@ -91,31 +61,34 @@ class StatActivityDuration implements ExportInterface
return 'activity';
}
public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
public function initiateQuery(array $requiredModifiers, array $acl, array $data = [])
{
$centers = array_map(function($el) { return $el['center']; }, $acl);
$centers = array_map(
static fn(array $el): string => $el['center'],
$acl
);
$qb = $this->entityManager->createQueryBuilder();
$select = null;
if ($this->action === self::SUM) {
$select = "SUM(activity.durationTime) AS export_stat_activity";
$select = 'SUM(activity.durationTime) AS export_stat_activity';
}
$qb->select($select)
->from('ChillActivityBundle:Activity', 'activity')
->join('activity.person', 'person')
->join('person.center', 'center')
->where($qb->expr()->in('center', ':centers'))
->setParameter(':centers', $centers)
;
return $qb;
return $qb->select($select)
->from('ChillActivityBundle:Activity', 'activity')
->join('activity.person', 'person')
->join('person.center', 'center')
->where($qb->expr()->in('center', ':centers'))
->setParameter(':centers', $centers);
}
public function supportsModifiers()
{
return array('person', 'activity');
return ['person', 'activity'];
}
public function requiredRole()
{
return new Role(ActivityStatsVoter::STATS);
@ -129,26 +102,17 @@ class StatActivityDuration implements ExportInterface
public function getLabels($key, array $values, $data)
{
if ($key !== 'export_stat_activity') {
throw new \LogicException("the key $key is not used by this export");
throw new \LogicException(sprintf('The key %s is not used by this export', $key));
}
switch ($this->action) {
case self::SUM:
$header = "Sum of activities duration";
}
return function($value) use ($header) {
return $value === '_header' ?
$header
:
$value
;
};
$header = $this->action === self::SUM ? 'Sum of activities duration' : false;
return static fn(string $value) => $value === '_header' ? $header : $value;
}
public function getQueryKeys($data)
{
return array('export_stat_activity');
return ['export_stat_activity'];
}
public function getResult($qb, $data)

View File

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

View File

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

View File

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

View File

@ -1,27 +1,13 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Command;
use Chill\MainBundle\Doctrine\Model\Point;
use Chill\MainBundle\Entity\Country;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
@ -31,38 +17,19 @@ use Symfony\Component\Filesystem\Filesystem;
use Chill\MainBundle\Entity\PostalCode;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class LoadPostalCodesCommand
*
* @package Chill\MainBundle\Command
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class LoadPostalCodesCommand extends Command
{
/**
* @var EntityManager
*/
private $entityManager;
/**
* @var ValidatorInterface
*/
private $validator;
/**
* LoadPostalCodesCommand constructor.
*
* @param EntityManager $entityManager
* @param ValidatorInterface $validator
*/
public function __construct(EntityManager $entityManager, ValidatorInterface $validator)
private EntityManagerInterface $entityManager;
private ValidatorInterface $validator;
public function __construct(EntityManagerInterface $entityManager, ValidatorInterface $validator)
{
$this->entityManager = $entityManager;
$this->validator = $validator;
parent::__construct();
}
protected function configure()
{
$this->setName('chill:main:postal-code:populate')
@ -78,10 +45,10 @@ class LoadPostalCodesCommand extends Command
->addArgument('csv_file', InputArgument::REQUIRED, "the path to "
. "the csv file. See the help for specifications.")
->addOption(
'delimiter',
'd',
InputOption::VALUE_OPTIONAL,
"The delimiter character of the csv file",
'delimiter',
'd',
InputOption::VALUE_OPTIONAL,
"The delimiter character of the csv file",
",")
->addOption(
'enclosure',
@ -99,31 +66,26 @@ class LoadPostalCodesCommand extends Command
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
try {
$csv = $this->getCSVResource($input);
} catch (\RuntimeException $e) {
$output->writeln('<error>Error during opening the csv file : '.
$e->getMessage().'</error>');
}
$csv = $this->getCSVResource($input);
if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) {
$output->writeln('The content of the file is ...');
$output->write(file_get_contents($input->getArgument('csv_file')));
}
$num = 0;
$line = 0;
while (($row = fgetcsv(
$csv,
0,
$input->getOption('delimiter'),
$input->getOption('enclosure'),
$csv,
0,
$input->getOption('delimiter'),
$input->getOption('enclosure'),
$input->getOption('escape'))) !== false) {
try{
$this->addPostalCode($row, $output);
$num++;
@ -136,31 +98,31 @@ class LoadPostalCodesCommand extends Command
}
$line ++;
}
$this->entityManager->flush();
$output->writeln('<info>'.$num.' were added !</info>');
}
private function getCSVResource(InputInterface $input)
{
$fs = new Filesystem();
$filename = $input->getArgument('csv_file');
if (!$fs->exists($filename)) {
throw new \RuntimeException("The file does not exists or you do not "
. "have the right to read it.");
}
$resource = fopen($filename, 'r');
if ($resource == FALSE) {
throw new \RuntimeException("The file '$filename' could not be opened.");
}
return $resource;
}
private function addPostalCode($row, OutputInterface $output)
{
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
@ -170,28 +132,28 @@ class LoadPostalCodesCommand extends Command
$country = $em
->getRepository(Country::class)
->findOneBy(array('countryCode' => $row[2]));
if ($country === NULL) {
throw new CountryCodeNotFoundException(sprintf("The country with code %s is not found. Aborting to insert postal code with %s - %s",
$row[2], $row[0], $row[1]));
}
// try to find an existing postal code
$existingPC = $em
->getRepository(PostalCode::class)
->findBy(array('code' => $row[0], 'name' => $row[1]));
if (count($existingPC) > 0) {
throw new ExistingPostalCodeException(sprintf("A postal code with code : %s and name : %s already exists, skipping",
throw new ExistingPostalCodeException(sprintf("A postal code with code : %s and name : %s already exists, skipping",
$row[0], $row[1]));
}
$postalCode = (new PostalCode())
->setCode($row[0])
->setName($row[1])
->setCountry($country)
;
if (NULL != $row[3]){
$postalCode->setRefPostalCodeId($row[3]);
}
@ -205,7 +167,7 @@ class LoadPostalCodesCommand extends Command
}
$errors = $this->validator->validate($postalCode);
if ($errors->count() == 0) {
$em->persist($postalCode);
} else {
@ -213,12 +175,12 @@ class LoadPostalCodesCommand extends Command
foreach ($errors as $error) {
$msg .= " ".$error->getMessage();
}
throw new PostalCodeNotValidException($msg);
}
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$output->writeln(sprintf('Creating postal code with code: %s, name: %s, countryCode: %s',
$postalCode->getCode(), $postalCode->getName(), $postalCode->getCountry()->getCountryCode()));
@ -229,15 +191,15 @@ class LoadPostalCodesCommand extends Command
class ExistingPostalCodeException extends \Exception
{
}
class CountryCodeNotFoundException extends \Exception
{
}
class PostalCodeNotValidException extends \Exception
{
}

View File

@ -1,58 +1,43 @@
<?php
/*
* Chill is a software for social workers
* Copyright (C) 2018 Champs-Libres Coopérative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\DQL;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\PathExpression;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
/**
* DQL function for OVERLAPS function in postgresql
*
* If a value is null in period start, it will be replaced by -infinity.
*
* If a value is null in period start, it will be replaced by -infinity.
* If a value is null in period end, it will be replaced by infinity
*
*/
class OverlapsI extends FunctionNode
{
private $firstPeriodStart;
private $firstPeriodEnd;
private $secondPeriodStart;
private $secondPeriodEnd;
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return '('
.$this->makeCase($sqlWalker, $this->firstPeriodStart, 'start').', '
.$this->makeCase($sqlWalker, $this->firstPeriodEnd, 'end').
') OVERLAPS ('
.$this->makeCase($sqlWalker, $this->secondPeriodStart, 'start').', '
.$this->makeCase($sqlWalker, $this->secondPeriodEnd, 'end').')'
;
return sprintf(
'(%s, %s) OVERLAPS (%s, %s)',
$this->makeCase($sqlWalker, $this->firstPeriodStart, 'start'),
$this->makeCase($sqlWalker, $this->firstPeriodEnd, 'end'),
$this->makeCase($sqlWalker, $this->secondPeriodStart, 'start'),
$this->makeCase($sqlWalker, $this->secondPeriodEnd, 'end')
);
}
protected function makeCase($sqlWalker, $part, $position)
protected function makeCase($sqlWalker, $part, string $position): string
{
//return $part->dispatch($sqlWalker);
switch ($position) {
case 'start' :
$p = '-infinity';
@ -60,51 +45,51 @@ class OverlapsI extends FunctionNode
case 'end':
$p = 'infinity';
break;
default:
throw new \Exception('Unexpected position value.');
}
if ($part instanceof \Doctrine\ORM\Query\AST\PathExpression) {
return 'CASE WHEN '
.' '.$part->dispatch($sqlWalker).' IS NOT NULL '
. 'THEN '.
$part->dispatch($sqlWalker)
. ' ELSE '.
"'".$p."'::date "
. 'END';
} else {
return 'CASE WHEN '
.' '.$part->dispatch($sqlWalker).'::date IS NOT NULL '
. 'THEN '.
$part->dispatch($sqlWalker)
. '::date ELSE '.
"'".$p."'::date "
. 'END';
if ($part instanceof PathExpression) {
return sprintf(
"CASE WHEN %s IS NOT NULL THEN %s ELSE '%s'::date END",
$part->dispatch($sqlWalker),
$part->dispatch($sqlWalker),
$p
);
}
return sprintf(
"CASE WHEN %s::date IS NOT NULL THEN %s::date ELSE '%s'::date END",
$part->dispatch($sqlWalker),
$part->dispatch($sqlWalker),
$p
);
}
public function parse(\Doctrine\ORM\Query\Parser $parser)
public function parse(Parser $parser): void
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->firstPeriodStart = $parser->StringPrimary();
$parser->match(Lexer::T_COMMA);
$this->firstPeriodEnd = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
$parser->match(Lexer::T_COMMA);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->secondPeriodStart = $parser->StringPrimary();
$parser->match(Lexer::T_COMMA);
$this->secondPeriodEnd = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}

View File

@ -1,48 +1,25 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Export\Formatter;
use Chill\MainBundle\Export\ExportInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// command to get the report with curl : curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* Command to get the report with curl:
* curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff
* @deprecated this formatter is not used any more.
*/
class CSVFormatter implements FormatterInterface
{
/**
*
* @var TranslatorInterface
*/
protected $translator;
protected TranslatorInterface $translator;
protected $result;
@ -85,11 +62,7 @@ class CSVFormatter implements FormatterInterface
}
/**
*
* @uses appendAggregatorForm
* @param FormBuilderInterface $builder
* @param type $exportAlias
* @param array $aggregatorAliases
*/
public function buildForm(FormBuilderInterface $builder, $exportAlias, array $aggregatorAliases)
{
@ -172,20 +145,35 @@ class CSVFormatter implements FormatterInterface
* If two aggregators have the same order, the second given will be placed
* after. This is not significant for the first ordering.
*
* @param type $formatterData
* @return type
*/
protected function orderingHeaders($formatterData)
protected function orderingHeaders(array $formatterData)
{
$this->formatterData = $formatterData;
uasort($this->formatterData, function($a, $b) {
uasort(
$this->formatterData,
static fn(array $a, array $b): int => ($a['order'] <= $b['order'] ? -1 : 1)
);
}
return ($a['order'] <= $b['order'] ? -1 : 1);
});
private function findColumnPosition(&$columnHeaders, $columnToFind): int
{
$i = 0;
foreach($columnHeaders as $set) {
if ($set === $columnToFind) {
return $i;
}
$i++;
}
//we didn't find it, adding the column
$columnHeaders[] = $columnToFind;
return $i++;
}
protected function generateContent()
{
$line = null;
$rowKeysNb = count($this->getRowHeaders());
$columnKeysNb = count($this->getColumnHeaders());
$resultsKeysNb = count($this->export->getQueryKeys($this->exportData));
@ -196,21 +184,6 @@ class CSVFormatter implements FormatterInterface
$contentData = array();
$content = array();
function findColumnPosition(&$columnHeaders, $columnToFind) {
$i = 0;
foreach($columnHeaders as $set) {
if ($set === $columnToFind) {
return $i;
}
$i++;
}
//we didn't find it, adding the column
$columnHeaders[] = $columnToFind;
return $i++;
}
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
@ -244,7 +217,7 @@ class CSVFormatter implements FormatterInterface
// add the column headers
/* @var $columns string[] the column for this row */
$columns = array_slice($row, $rowKeysNb, $columnKeysNb);
$columnPosition = findColumnPosition($columnHeaders, $columns);
$columnPosition = $this->findColumnPosition($columnHeaders, $columns);
//fill with blank at the position given by the columnPosition + nbRowHeaders
for ($i=0; $i < $columnPosition; $i++) {

View File

@ -4,6 +4,8 @@ namespace Chill\PersonBundle\Command;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
@ -360,6 +362,7 @@ EOF
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$headers = $rawHeaders = [];
$this->input = $input;
$this->output = $output;
@ -453,15 +456,15 @@ EOF
}
/**
*
* @param type $firstRow
* @return array where keys are column number, and value is information mapped
*/
protected function processingHeaders($firstRow)
protected function processingHeaders(array $firstRow): array
{
$availableOptions = array_map(function($m) { return $m[0]; }, self::$mapping);
$matchedColumnHeaders = array();
$headers = array();
$availableOptions = array_map(
static fn (array $m) => $m[0],
self::$mapping
);
$matchedColumnHeaders = $headers = [];
foreach($availableOptions as $option) {
$matchedColumnHeaders[$option] = $this->input->getOption($option);
@ -482,13 +485,10 @@ EOF
}
/**
*
* @param array $row
* @param array $headers the processed header : an array as prepared by self::processingHeaders
* @return Person
* @throws \Exception
*/
protected function createPerson($row, $headers)
protected function createPerson(array $row, array $headers): Person
{
// trying to get the opening date
$openingDateString = trim($row[array_search('opening_date', $headers)]);
@ -580,30 +580,27 @@ EOF
}
/**
* @param $row
* @param $headers
* @return Center|mixed|null|object
*/
protected function getCenter($row, $headers)
protected function getCenter(array $row, array $headers)
{
if ($this->input->hasOption('force-center') && !empty($this->input->getOption('force-center'))) {
return $this->em->getRepository('ChillMainBundle:Center')
->find($this->input->getOption('force-center'));
} else {
$columnCenter = \array_search('center', $headers);
$centerName = \trim($row[$columnCenter]);
return $this->em->getRepository(Center::class)->find($this->input->getOption('force-center'));
}
try {
return $this->em->createQuery('SELECT c FROM ChillMainBundle:Center c '
. 'WHERE c.name = :center_name')
->setParameter('center_name', $centerName)
->getSingleResult()
;
} catch (\Doctrine\ORM\NonUniqueResultException $e) {
return $this->guessCenter($centerName);
} catch (\Doctrine\ORM\NoResultException $e) {
return $this->guessCenter($centerName);
}
$columnCenter = array_search('center', $headers);
$centerName = trim($row[$columnCenter]);
try {
return $this
->em
->createQuery('SELECT c FROM ChillMainBundle:Center c WHERE c.name = :center_name')
->setParameter('center_name', $centerName)
->getSingleResult();
} catch (NonUniqueResultException $e) {
return $this->guessCenter($centerName);
} catch (NoResultException $e) {
return $this->guessCenter($centerName);
}
}

View File

@ -76,13 +76,12 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
{
/**
* The person's id
* @var integer
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
private int $id;
/**
* The person's first name
@ -732,12 +731,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return false;
}
/**
* Get id
*
* @return integer
*/
public function getId()
public function getId(): int
{
return $this->id;
}
@ -1846,7 +1840,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
{
return $this->updatedBy;
}
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updatedAt;

View File

@ -274,6 +274,8 @@ final class SocialWorkMetadata implements SocialWorkMetadataInterface
$jsonCriterias
);
$entity = null;
switch (true) {
case count($results) === 0:
$entity = $repository->getClassName();
@ -291,6 +293,10 @@ final class SocialWorkMetadata implements SocialWorkMetadataInterface
);
}
if (null === $entity) {
throw new Exception('Unable to create entity.');
}
return $entity;
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace Chill\TaskBundle\Controller;
use Chill\MainBundle\Entity\Scope;
@ -41,14 +43,8 @@ use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface as TranslationTranslatorInterface;
/**
* Class SingleTaskController
*
* @package Chill\TaskBundle\Controller
*/
final class SingleTaskController extends AbstractController
{
private EventDispatcherInterface $eventDispatcher;
private TimelineBuilder $timelineBuilder;
private LoggerInterface $logger;
@ -332,15 +328,12 @@ final class SingleTaskController extends AbstractController
* name="chill_task_single_task_delete"
* )
*/
public function deleteAction(
Request $request,
$id
) {
public function deleteAction(Request $request, $id) {
$course = null;
$em = $this->getDoctrine()->getManager();
$task = $em->getRepository(SingleTask::class)->find($id);
if (!$task) {
if (null === $task) {
throw $this->createNotFoundException('Unable to find Task entity.');
}
@ -415,19 +408,24 @@ final class SingleTaskController extends AbstractController
}
}
if($task->getContext() instanceof Person){
return $this->render('@ChillTask/SingleTask/Person/confirm_delete.html.twig', array(
'task' => $task,
'delete_form' => $form->createView()
));
} else {
return $this->render('@ChillTask/SingleTask/AccompanyingCourse/confirm_delete.html.twig', array(
'task' => $task,
'delete_form' => $form->createView(),
'accompanyingCourse' => $course
));
if ($task->getContext() instanceof Person) {
return $this->render(
'@ChillTask/SingleTask/Person/confirm_delete.html.twig',
[
'task' => $task,
'delete_form' => $form->createView(),
]
);
}
return $this->render(
'@ChillTask/SingleTask/AccompanyingCourse/confirm_delete.html.twig',
[
'task' => $task,
'delete_form' => $form->createView(),
'accompanyingCourse' => $course
]
);
}
/**

View File

@ -1,20 +1,7 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Chill\TaskBundle\Form;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
@ -48,6 +35,9 @@ class SingleTaskType extends AbstractType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$center = null;
$isScopeConcerned = false;
if (NULL !== $task = $options['data']) {
$center = $this->centerResolverDispatcher->resolveCenter($task);
$isScopeConcerned = $this->scopeResolverDispatcher->isConcerned($task);
@ -74,8 +64,7 @@ class SingleTaskType extends AbstractType
'required' => false
]);
if ($this->parameterBag->get('chill_main')['acl']['form_show_scopes']
&& $isScopeConcerned) {
if ($isScopeConcerned && $this->parameterBag->get('chill_main')['acl']['form_show_scopes']) {
$builder
->add('circle', ScopePickerType::class, [
'center' => $center,