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: parameters:
ignoreErrors: 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\\.$#" message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1 count: 1
@ -50,16 +40,6 @@ parameters:
count: 1 count: 1
path: src/Bundle/ChillActivityBundle/Export/Export/StatActivityDuration.php 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\\.$#" message: "#^Call to function in_array\\(\\) requires parameter \\#3 to be set\\.$#"
count: 1 count: 1
@ -155,11 +135,6 @@ parameters:
count: 2 count: 2
path: src/Bundle/ChillBudgetBundle/Security/Authorization/BudgetElementVoter.php 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\\.$#" message: "#^Access to an undefined property Chill\\\\CalendarBundle\\\\DataFixtures\\\\ORM\\\\LoadCalendarRange\\:\\:\\$userRepository\\.$#"
count: 2 count: 2
@ -260,11 +235,6 @@ parameters:
count: 1 count: 1
path: src/Bundle/ChillCustomFieldsBundle/Form/CustomFieldType.php 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\\.$#" message: "#^Call to sprintf contains 0 placeholders, 1 value given\\.$#"
count: 1 count: 1
@ -535,11 +505,6 @@ parameters:
count: 1 count: 1
path: src/Bundle/ChillMainBundle/Command/LoadPostalCodesCommand.php 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\\.$#" message: "#^Method Chill\\\\MainBundle\\\\Command\\\\SetPasswordCommand\\:\\:execute\\(\\) should return int but return statement is missing\\.$#"
count: 1 count: 1
@ -620,11 +585,6 @@ parameters:
count: 1 count: 1
path: src/Bundle/ChillMainBundle/DependencyInjection/Widget/AbstractWidgetsCompilerPass.php 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\\(\\)\\.$#" message: "#^Method Chill\\\\MainBundle\\\\Doctrine\\\\Type\\\\PointType\\:\\:getSqlDeclaration\\(\\) does not match parent method name\\: Doctrine\\\\DBAL\\\\Types\\\\Type\\:\\:getSQLDeclaration\\(\\)\\.$#"
count: 1 count: 1
@ -661,23 +621,8 @@ parameters:
path: src/Bundle/ChillMainBundle/Export/ExportManager.php path: src/Bundle/ChillMainBundle/Export/ExportManager.php
- -
message: "#^Function findColumnPosition not found\\.$#" message: "#^Foreach overwrites \\$line with its value variable\\.$#"
count: 1 count: 2
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
path: src/Bundle/ChillMainBundle/Export/Formatter/CSVFormatter.php path: src/Bundle/ChillMainBundle/Export/Formatter/CSVFormatter.php
- -
@ -940,16 +885,6 @@ parameters:
count: 6 count: 6
path: src/Bundle/ChillPersonBundle/Command/ImportPeopleFromCSVCommand.php 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\\.$#" message: "#^Variable \\$street1Value might not be defined\\.$#"
count: 1 count: 1
@ -1255,11 +1190,6 @@ parameters:
count: 2 count: 2
path: src/Bundle/ChillPersonBundle/Serializer/Normalizer/PersonNormalizer.php 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\\.$#" message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 2 count: 2
@ -1370,11 +1300,6 @@ parameters:
count: 4 count: 4
path: src/Bundle/ChillReportBundle/Timeline/TimelineReportProvider.php 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$#" message: "#^Undefined variable\\: \\$type$#"
count: 1 count: 1
@ -1400,16 +1325,6 @@ parameters:
count: 2 count: 2
path: src/Bundle/ChillTaskBundle/Form/SingleTaskListType.php 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\\.$#" message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1 count: 1

View File

@ -1,28 +1,9 @@
<?php <?php
/* declare(strict_types=1);
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\ActivityBundle\Controller; namespace Chill\ActivityBundle\Controller;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepository;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepositoryInterface; use Chill\ActivityBundle\Repository\ActivityACLAwareRepositoryInterface;
use Chill\ActivityBundle\Security\Authorization\ActivityVoter; use Chill\ActivityBundle\Security\Authorization\ActivityVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper; use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
@ -42,12 +23,7 @@ use Chill\ActivityBundle\Form\ActivityType;
use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable; use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\SerializerInterface;
/** final class ActivityController extends AbstractController
* Class ActivityController
*
* @package Chill\ActivityBundle\Controller
*/
class ActivityController extends AbstractController
{ {
protected EventDispatcherInterface $eventDispatcher; protected EventDispatcherInterface $eventDispatcher;
@ -78,8 +54,8 @@ class ActivityController extends AbstractController
*/ */
public function listAction(Request $request): Response public function listAction(Request $request): Response
{ {
$em = $this->getDoctrine()->getManager();
$view = null; $view = null;
$activities = [];
// TODO: add pagination // TODO: add pagination
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@ -105,11 +81,14 @@ class ActivityController extends AbstractController
$view = 'ChillActivityBundle:Activity:listAccompanyingCourse.html.twig'; $view = 'ChillActivityBundle:Activity:listAccompanyingCourse.html.twig';
} }
return $this->render($view, array( return $this->render(
'activities' => $activities, $view,
'person' => $person, [
'accompanyingCourse' => $accompanyingPeriod, 'activities' => $activities,
)); 'person' => $person,
'accompanyingCourse' => $accompanyingPeriod,
]
);
} }
public function selectTypeAction(Request $request): Response public function selectTypeAction(Request $request): Response
@ -160,6 +139,7 @@ class ActivityController extends AbstractController
public function newAction(Request $request): Response public function newAction(Request $request): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@ -297,6 +277,7 @@ class ActivityController extends AbstractController
public function showAction(Request $request, $id): Response public function showAction(Request $request, $id): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@ -351,6 +332,7 @@ class ActivityController extends AbstractController
*/ */
public function editAction($id, Request $request): Response public function editAction($id, Request $request): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);
@ -422,6 +404,7 @@ class ActivityController extends AbstractController
*/ */
public function deleteAction(Request $request, $id) public function deleteAction(Request $request, $id)
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$person, $accompanyingPeriod] = $this->getEntity($request); [$person, $accompanyingPeriod] = $this->getEntity($request);

View File

@ -1,21 +1,6 @@
<?php <?php
/* declare(strict_types=1);
* Copyright (C) 2015 Champs-Libres <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\ActivityBundle\Export\Export; namespace Chill\ActivityBundle\Export\Export;
@ -30,37 +15,22 @@ use Doctrine\ORM\EntityManagerInterface;
* This export allow to compute stats on activity duration. * This export allow to compute stats on activity duration.
* *
* The desired stat must be given in constructor. * The desired stat must be given in constructor.
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
class StatActivityDuration implements ExportInterface class StatActivityDuration implements ExportInterface
{ {
/** protected EntityManagerInterface $entityManager;
*
* @var EntityManagerInterface
*/
protected $entityManager;
const SUM = 'sum'; public const SUM = 'sum';
/** /**
* The action for this report. * The action for this report.
*
* @var string
*/ */
protected $action; protected string $action;
/** /**
* constructor
*
* @param EntityManagerInterface $em
* @param string $action the stat to perform * @param string $action the stat to perform
*/ */
public function __construct( public function __construct(EntityManagerInterface $em, string $action = 'sum')
EntityManagerInterface $em,
$action = 'sum'
)
{ {
$this->entityManager = $em; $this->entityManager = $em;
$this->action = $action; $this->action = $action;
@ -74,14 +44,14 @@ class StatActivityDuration implements ExportInterface
public function getDescription() public function getDescription()
{ {
if ($this->action === self::SUM) { if ($this->action === self::SUM) {
return "Sum activities duration by various parameters."; return 'Sum activities duration by various parameters.';
} }
} }
public function getTitle() public function getTitle()
{ {
if ($this->action === self::SUM) { if ($this->action === self::SUM) {
return "Sum activity duration"; return 'Sum activity duration';
} }
} }
@ -91,29 +61,32 @@ class StatActivityDuration implements ExportInterface
return 'activity'; 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(); $qb = $this->entityManager->createQueryBuilder();
$select = null;
if ($this->action === self::SUM) { if ($this->action === self::SUM) {
$select = "SUM(activity.durationTime) AS export_stat_activity"; $select = 'SUM(activity.durationTime) AS export_stat_activity';
} }
$qb->select($select) return $qb->select($select)
->from('ChillActivityBundle:Activity', 'activity') ->from('ChillActivityBundle:Activity', 'activity')
->join('activity.person', 'person') ->join('activity.person', 'person')
->join('person.center', 'center') ->join('person.center', 'center')
->where($qb->expr()->in('center', ':centers')) ->where($qb->expr()->in('center', ':centers'))
->setParameter(':centers', $centers) ->setParameter(':centers', $centers);
;
return $qb;
} }
public function supportsModifiers() public function supportsModifiers()
{ {
return array('person', 'activity'); return ['person', 'activity'];
} }
public function requiredRole() public function requiredRole()
@ -129,26 +102,17 @@ class StatActivityDuration implements ExportInterface
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data)
{ {
if ($key !== 'export_stat_activity') { if ($key !== 'export_stat_activity') {
throw new \LogicException("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) { $header = $this->action === self::SUM ? 'Sum of activities duration' : false;
case self::SUM:
$header = "Sum of activities duration";
}
return function($value) use ($header) { return static fn(string $value) => $value === '_header' ? $header : $value;
return $value === '_header' ?
$header
:
$value
;
};
} }
public function getQueryKeys($data) public function getQueryKeys($data)
{ {
return array('export_stat_activity'); return ['export_stat_activity'];
} }
public function getResult($qb, $data) public function getResult($qb, $data)

View File

@ -1,24 +1,6 @@
<?php <?php
/* declare(strict_types=1);
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\CalendarBundle\Controller; namespace Chill\CalendarBundle\Controller;
@ -26,9 +8,11 @@ use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Privacy\PrivacyEvent; use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Form; use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@ -42,11 +26,6 @@ use Chill\MainBundle\Pagination\PaginatorFactory;
use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
/**
* Class CalendarController
*
* @package Chill\CalendarBundle\Controller
*/
class CalendarController extends AbstractController class CalendarController extends AbstractController
{ {
protected EventDispatcherInterface $eventDispatcher; protected EventDispatcherInterface $eventDispatcher;
@ -127,6 +106,7 @@ class CalendarController extends AbstractController
*/ */
public function newAction(Request $request): Response public function newAction(Request $request): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@ -163,10 +143,11 @@ class CalendarController extends AbstractController
$params = $this->buildParamsToUrl($user, $accompanyingPeriod); $params = $this->buildParamsToUrl($user, $accompanyingPeriod);
return $this->redirectToRoute('chill_calendar_calendar_list', $params); return $this->redirectToRoute('chill_calendar_calendar_list', $params);
} elseif ($form->isSubmitted() and !$form->isValid()) {
$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) { if ($view === null) {
throw $this->createNotFoundException('Template not found'); throw $this->createNotFoundException('Template not found');
@ -189,6 +170,7 @@ class CalendarController extends AbstractController
*/ */
public function showAction(Request $request, $id): Response public function showAction(Request $request, $id): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@ -200,33 +182,37 @@ class CalendarController extends AbstractController
$view = '@ChillCalendar/Calendar/showByUser.html.twig'; $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) { if ($view === null) {
throw $this->createNotFoundException('Template not found'); throw $this->createNotFoundException('Template not found');
} }
$personsId = []; /** @var Calendar $entity */
foreach ($entity->getPersons() as $p) { $entity = $em->getRepository('ChillCalendarBundle:Calendar')->find($id);
array_push($personsId, $p->getId());
if (null === $entity) {
throw $this->createNotFoundException('Unable to find Calendar entity.');
} }
$professionalsId = []; if (null !== $accompanyingPeriod) {
foreach ($entity->getProfessionals() as $p) { // @TODO: These properties are declared dynamically.
array_push($professionalsId, $p->getId()); // 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()); $durationTime = $entity->getEndDate()->diff($entity->getStartDate());
$durationTimeInMinutes = $durationTime->days*1440 + $durationTime->h*60 + $durationTime->i; $durationTimeInMinutes = $durationTime->days*1440 + $durationTime->h*60 + $durationTime->i;
@ -242,7 +228,7 @@ class CalendarController extends AbstractController
return $this->render($view, [ return $this->render($view, [
'accompanyingCourse' => $accompanyingPeriod, 'accompanyingCourse' => $accompanyingPeriod,
'entity' => $entity, 'entity' => $entity,
'user' => $user, 'user' => $user,
'activityData' => $activityData 'activityData' => $activityData
//'delete_form' => $deleteForm->createView(), //'delete_form' => $deleteForm->createView(),
@ -257,6 +243,7 @@ class CalendarController extends AbstractController
*/ */
public function editAction($id, Request $request): Response public function editAction($id, Request $request): Response
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@ -285,8 +272,11 @@ class CalendarController extends AbstractController
$this->addFlash('success', $this->get('translator')->trans('Success : calendar item updated!')); $this->addFlash('success', $this->get('translator')->trans('Success : calendar item updated!'));
$params = $this->buildParamsToUrl($user, $accompanyingPeriod); $params = $this->buildParamsToUrl($user, $accompanyingPeriod);
return $this->redirectToRoute('chill_calendar_calendar_list', $params); return $this->redirectToRoute('chill_calendar_calendar_list', $params);
} elseif ($form->isSubmitted() and !$form->isValid()) { }
if ($form->isSubmitted() and !$form->isValid()) {
$this->addFlash('error', $this->get('translator')->trans('This form contains errors')); $this->addFlash('error', $this->get('translator')->trans('This form contains errors'));
} }
@ -314,6 +304,7 @@ class CalendarController extends AbstractController
*/ */
public function deleteAction(Request $request, $id) public function deleteAction(Request $request, $id)
{ {
$view = null;
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
[$user, $accompanyingPeriod] = $this->getEntity($request); [$user, $accompanyingPeriod] = $this->getEntity($request);
@ -369,7 +360,7 @@ class CalendarController extends AbstractController
/** /**
* Creates a form to delete a Calendar entity by id. * Creates a form to delete a Calendar entity by id.
*/ */
private function createDeleteForm(int $id, ?User $user, ?AccompanyingPeriod $accompanyingPeriod): Form private function createDeleteForm(int $id, ?User $user, ?AccompanyingPeriod $accompanyingPeriod): FormInterface
{ {
$params = $this->buildParamsToUrl($user, $accompanyingPeriod); $params = $this->buildParamsToUrl($user, $accompanyingPeriod);
$params['id'] = $id; $params['id'] = $id;
@ -416,17 +407,14 @@ class CalendarController extends AbstractController
]; ];
} }
private function buildParamsToUrl( private function buildParamsToUrl(?User $user, ?AccompanyingPeriod $accompanyingPeriod): array {
?User $user,
?AccompanyingPeriod $accompanyingPeriod
): array {
$params = []; $params = [];
if ($user) { if (null !== $user) {
$params['user_id'] = $user->getId(); $params['user_id'] = $user->getId();
} }
if ($accompanyingPeriod) { if (null !== $accompanyingPeriod) {
$params['accompanying_period_id'] = $accompanyingPeriod->getId(); $params['accompanying_period_id'] = $accompanyingPeriod->getId();
} }

View File

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

View File

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

View File

@ -1,27 +1,13 @@
<?php <?php
/* declare(strict_types=1);
* Copyright (C) 2016 Champs-Libres <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Command; namespace Chill\MainBundle\Command;
use Chill\MainBundle\Doctrine\Model\Point; use Chill\MainBundle\Doctrine\Model\Point;
use Chill\MainBundle\Entity\Country; use Chill\MainBundle\Entity\Country;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
@ -31,32 +17,13 @@ use Symfony\Component\Filesystem\Filesystem;
use Chill\MainBundle\Entity\PostalCode; use Chill\MainBundle\Entity\PostalCode;
use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class LoadPostalCodesCommand
*
* @package Chill\MainBundle\Command
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class LoadPostalCodesCommand extends Command class LoadPostalCodesCommand extends Command
{ {
private EntityManagerInterface $entityManager;
/** private ValidatorInterface $validator;
* @var EntityManager
*/
private $entityManager;
/** public function __construct(EntityManagerInterface $entityManager, ValidatorInterface $validator)
* @var ValidatorInterface
*/
private $validator;
/**
* LoadPostalCodesCommand constructor.
*
* @param EntityManager $entityManager
* @param ValidatorInterface $validator
*/
public function __construct(EntityManager $entityManager, ValidatorInterface $validator)
{ {
$this->entityManager = $entityManager; $this->entityManager = $entityManager;
$this->validator = $validator; $this->validator = $validator;
@ -102,12 +69,7 @@ class LoadPostalCodesCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
try { $csv = $this->getCSVResource($input);
$csv = $this->getCSVResource($input);
} catch (\RuntimeException $e) {
$output->writeln('<error>Error during opening the csv file : '.
$e->getMessage().'</error>');
}
if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) { if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) {
$output->writeln('The content of the file is ...'); $output->writeln('The content of the file is ...');

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Chill\TaskBundle\Controller; namespace Chill\TaskBundle\Controller;
use Chill\MainBundle\Entity\Scope; use Chill\MainBundle\Entity\Scope;
@ -41,14 +43,8 @@ use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface as TranslationTranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface as TranslationTranslatorInterface;
/**
* Class SingleTaskController
*
* @package Chill\TaskBundle\Controller
*/
final class SingleTaskController extends AbstractController final class SingleTaskController extends AbstractController
{ {
private EventDispatcherInterface $eventDispatcher; private EventDispatcherInterface $eventDispatcher;
private TimelineBuilder $timelineBuilder; private TimelineBuilder $timelineBuilder;
private LoggerInterface $logger; private LoggerInterface $logger;
@ -332,15 +328,12 @@ final class SingleTaskController extends AbstractController
* name="chill_task_single_task_delete" * name="chill_task_single_task_delete"
* ) * )
*/ */
public function deleteAction( public function deleteAction(Request $request, $id) {
Request $request, $course = null;
$id
) {
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
$task = $em->getRepository(SingleTask::class)->find($id); $task = $em->getRepository(SingleTask::class)->find($id);
if (!$task) { if (null === $task) {
throw $this->createNotFoundException('Unable to find Task entity.'); throw $this->createNotFoundException('Unable to find Task entity.');
} }
@ -415,19 +408,24 @@ final class SingleTaskController extends AbstractController
} }
} }
if($task->getContext() instanceof Person){ if ($task->getContext() instanceof Person) {
return $this->render('@ChillTask/SingleTask/Person/confirm_delete.html.twig', array( return $this->render(
'task' => $task, '@ChillTask/SingleTask/Person/confirm_delete.html.twig',
'delete_form' => $form->createView() [
)); 'task' => $task,
} else { 'delete_form' => $form->createView(),
return $this->render('@ChillTask/SingleTask/AccompanyingCourse/confirm_delete.html.twig', array( ]
'task' => $task, );
'delete_form' => $form->createView(),
'accompanyingCourse' => $course
));
} }
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 <?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop> declare(strict_types=1);
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\TaskBundle\Form; namespace Chill\TaskBundle\Form;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher; use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
@ -48,6 +35,9 @@ class SingleTaskType extends AbstractType
public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
$center = null;
$isScopeConcerned = false;
if (NULL !== $task = $options['data']) { if (NULL !== $task = $options['data']) {
$center = $this->centerResolverDispatcher->resolveCenter($task); $center = $this->centerResolverDispatcher->resolveCenter($task);
$isScopeConcerned = $this->scopeResolverDispatcher->isConcerned($task); $isScopeConcerned = $this->scopeResolverDispatcher->isConcerned($task);
@ -74,8 +64,7 @@ class SingleTaskType extends AbstractType
'required' => false 'required' => false
]); ]);
if ($this->parameterBag->get('chill_main')['acl']['form_show_scopes'] if ($isScopeConcerned && $this->parameterBag->get('chill_main')['acl']['form_show_scopes']) {
&& $isScopeConcerned) {
$builder $builder
->add('circle', ScopePickerType::class, [ ->add('circle', ScopePickerType::class, [
'center' => $center, 'center' => $center,