Merge remote-tracking branch 'origin/master' into 616_rapid-action

This commit is contained in:
2024-06-12 16:45:43 +02:00
2249 changed files with 42970 additions and 30730 deletions

View File

@@ -16,32 +16,14 @@ use Chill\MainBundle\Entity\Notification;
use Chill\MainBundle\Notification\NotificationPersisterInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Event\Person\PersonAddressMoveEvent;
use DateTimeImmutable;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class PersonAddressMoveEventSubscriber implements EventSubscriberInterface
{
private EngineInterface $engine;
private NotificationPersisterInterface $notificationPersister;
private Security $security;
private TranslatorInterface $translator;
public function __construct(
EngineInterface $engine,
NotificationPersisterInterface $notificationPersister,
Security $security,
TranslatorInterface $translator
) {
$this->engine = $engine;
$this->notificationPersister = $notificationPersister;
$this->security = $security;
$this->translator = $translator;
public function __construct(private readonly \Twig\Environment $engine, private readonly NotificationPersisterInterface $notificationPersister, private readonly Security $security, private readonly TranslatorInterface $translator)
{
}
public static function getSubscribedEvents(): array
@@ -59,7 +41,7 @@ class PersonAddressMoveEventSubscriber implements EventSubscriberInterface
$person = $event->getPerson();
foreach ($person->getCurrentAccompanyingPeriods() as $period) {
if ($period->getStep() === AccompanyingPeriod::STEP_DRAFT) {
if (AccompanyingPeriod::STEP_DRAFT === $period->getStep()) {
continue;
}
@@ -67,7 +49,7 @@ class PersonAddressMoveEventSubscriber implements EventSubscriberInterface
$period->getPersonLocation() === $person
&& (
$event->getMoveDate() >= $period->getLastLocationHistory()->getStartDate()
|| $event->willChangeBeActiveAt(new DateTimeImmutable('now'))
|| $event->willChangeBeActiveAt(new \DateTimeImmutable('now'))
)
&& null !== $period->getUser()
&& $period->getUser() !== $this->security->getUser()

View File

@@ -18,26 +18,13 @@ use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Workflow\Event\EnteredEvent;
use Symfony\Contracts\Translation\TranslatorInterface;
class UserRefEventSubscriber implements EventSubscriberInterface
{
private EngineInterface $engine;
private NotificationPersisterInterface $notificationPersister;
private Security $security;
private TranslatorInterface $translator;
public function __construct(Security $security, TranslatorInterface $translator, EngineInterface $engine, NotificationPersisterInterface $notificationPersister)
public function __construct(private readonly Security $security, private readonly TranslatorInterface $translator, private readonly \Twig\Environment $engine, private readonly NotificationPersisterInterface $notificationPersister)
{
$this->security = $security;
$this->translator = $translator;
$this->engine = $engine;
$this->notificationPersister = $notificationPersister;
}
public static function getSubscribedEvents()
@@ -53,7 +40,7 @@ class UserRefEventSubscriber implements EventSubscriberInterface
{
if (
$enteredEvent->getMarking()->has(AccompanyingPeriod::STEP_CONFIRMED)
and $enteredEvent->getTransition()->getName() === 'confirm'
and 'confirm' === $enteredEvent->getTransition()->getName()
) {
$this->onPeriodConfirmed($enteredEvent->getSubject());
}
@@ -64,7 +51,7 @@ class UserRefEventSubscriber implements EventSubscriberInterface
if ($period->isChangedUser()
&& $period->getUser() !== $this->security->getUser()
&& null !== $period->getUser()
&& $period->getStep() !== AccompanyingPeriod::STEP_DRAFT
&& AccompanyingPeriod::STEP_DRAFT !== $period->getStep()
&& !$period->isPreventUserIsChangedNotification()
) {
$this->generateNotificationToUser($period);
@@ -76,12 +63,12 @@ class UserRefEventSubscriber implements EventSubscriberInterface
$notification = new Notification();
$urgentStatement =
$period->isEmergency() ? strtoupper($this->translator->trans('accompanying_period.emergency')) . ' ' : '';
$period->isEmergency() ? strtoupper($this->translator->trans('accompanying_period.emergency')).' ' : '';
$notification
->setRelatedEntityId($period->getId())
->setRelatedEntityClass(AccompanyingPeriod::class)
->setTitle($urgentStatement . $this->translator->trans('period_notification.period_designated_subject'))
->setTitle($urgentStatement.$this->translator->trans('period_notification.period_designated_subject'))
->setMessage($this->engine->render(
'@ChillPerson/Notification/accompanying_course_designation.md.twig',
[

View File

@@ -39,8 +39,10 @@ readonly class AccompanyingPeriodStepChangeCronjob implements CronJobInterface
return 'accompanying-period-step-change';
}
public function run(): void
public function run(array $lastExecutionData): ?array
{
($this->requestor)();
return null;
}
}

View File

@@ -21,15 +21,15 @@ class AccompanyingPeriodStepChangeMessageHandler implements MessageHandlerInterf
private const LOG_PREFIX = '[accompanying period step change message handler] ';
public function __construct(
private AccompanyingPeriodRepository $accompanyingPeriodRepository,
private AccompanyingPeriodStepChanger $changer,
private readonly AccompanyingPeriodRepository $accompanyingPeriodRepository,
private readonly AccompanyingPeriodStepChanger $changer,
) {
}
public function __invoke(AccompanyingPeriodStepChangeRequestMessage $message): void
{
if (null === $period = $this->accompanyingPeriodRepository->find($message->getPeriodId())) {
throw new \RuntimeException(self::LOG_PREFIX . 'Could not find period with this id: '. $message->getPeriodId());
throw new \RuntimeException(self::LOG_PREFIX.'Could not find period with this id: '.$message->getPeriodId());
}
($this->changer)($period, $message->getTransition());

View File

@@ -14,7 +14,7 @@ namespace Chill\PersonBundle\AccompanyingPeriod\Lifecycle;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
/**
* Message which will request a change in the step of accompanying period
* Message which will request a change in the step of accompanying period.
*/
class AccompanyingPeriodStepChangeRequestMessage
{
@@ -22,7 +22,7 @@ class AccompanyingPeriodStepChangeRequestMessage
public function __construct(
AccompanyingPeriod|int $period,
private string $transition,
private readonly string $transition,
) {
if (is_int($period)) {
$this->periodId = $period;
@@ -31,7 +31,7 @@ class AccompanyingPeriodStepChangeRequestMessage
$this->periodId = $id;
}
throw new \LogicException("This AccompanyingPeriod does not have and id yet");
throw new \LogicException('This AccompanyingPeriod does not have and id yet');
}
}

View File

@@ -13,26 +13,25 @@ namespace Chill\PersonBundle\AccompanyingPeriod\Lifecycle;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodInfoRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Messenger\MessageBusInterface;
/**
* Gather all the accompanying period which needs a change in step
* Gather all the accompanying period which needs a change in step.
*/
class AccompanyingPeriodStepChangeRequestor
{
private \DateInterval $intervalForShortInactive;
private readonly \DateInterval $intervalForShortInactive;
private \DateInterval $intervalForLongInactive;
private readonly \DateInterval $intervalForLongInactive;
private bool $isMarkInactive;
private readonly bool $isMarkInactive;
public function __construct(
private AccompanyingPeriodInfoRepositoryInterface $accompanyingPeriodInfoRepository,
private LoggerInterface $logger,
private MessageBusInterface $messageBus,
private readonly AccompanyingPeriodInfoRepositoryInterface $accompanyingPeriodInfoRepository,
private readonly LoggerInterface $logger,
private readonly MessageBusInterface $messageBus,
ParameterBagInterface $parameterBag,
) {
$config = $parameterBag->get('chill_person')['accompanying_period_lifecycle_delays'];

View File

@@ -17,7 +17,7 @@ use Psr\Log\LoggerInterface;
use Symfony\Component\Workflow\Registry;
/**
* Change the step of an accompanying period
* Change the step of an accompanying period.
*
* This should be invoked through scripts (not in the in context of an http request, or an
* action from a user).
@@ -27,9 +27,9 @@ class AccompanyingPeriodStepChanger
private const LOG_PREFIX = '[AccompanyingPeriodStepChanger] ';
public function __construct(
private EntityManagerInterface $entityManager,
private LoggerInterface $logger,
private Registry $workflowRegistry,
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
private readonly Registry $workflowRegistry,
) {
}
@@ -38,9 +38,9 @@ class AccompanyingPeriodStepChanger
$workflow = $this->workflowRegistry->get($period, $workflowName);
if (!$workflow->can($period, $transition)) {
$this->logger->info(self::LOG_PREFIX . 'not able to apply the transition on period', [
$this->logger->info(self::LOG_PREFIX.'not able to apply the transition on period', [
'period_id' => $period->getId(),
'transition' => $transition
'transition' => $transition,
]);
return;
@@ -50,9 +50,9 @@ class AccompanyingPeriodStepChanger
$this->entityManager->flush();
$this->logger->info(self::LOG_PREFIX . 'could apply a transition', [
$this->logger->info(self::LOG_PREFIX.'could apply a transition', [
'period_id' => $period->getId(),
'transition' => $transition
'transition' => $transition,
]);
}
}

View File

@@ -13,7 +13,6 @@ namespace Chill\PersonBundle\AccompanyingPeriod\SocialIssueConsistency;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;

View File

@@ -16,30 +16,11 @@ use Symfony\Component\EventDispatcher\Event;
/**
* Event triggered when an entity attached to a person is removed.
*/
class ActionEvent extends Event
class ActionEvent extends \Symfony\Contracts\EventDispatcher\Event
{
public const DELETE = 'CHILL_PERSON.DELETE_ASSOCIATED_ENTITY';
final public const DELETE = 'CHILL_PERSON.DELETE_ASSOCIATED_ENTITY';
public const MOVE = 'CHILL_PERSON.MOVE_ASSOCIATED_ENTITY';
/**
* the FQDN class name as recorded in doctrine.
*
* @var string
*/
protected $entity;
/**
* an array of key value data to describe the movement.
*
* @var array
*/
protected $metadata;
/**
* @var int
*/
protected $personId;
final public const MOVE = 'CHILL_PERSON.MOVE_ASSOCIATED_ENTITY';
/**
* @var string[]
@@ -52,18 +33,26 @@ class ActionEvent extends Event
protected $preSql = [];
/**
* the sql statement.
*
* @var string
* @param string $entity
* @param mixed[] $metadata
* @param int $personId
* @param string $sqlStatement
*/
protected $sqlStatement;
public function __construct($personId, $entity, $sqlStatement, $metadata = [])
{
$this->personId = $personId;
$this->entity = $entity;
$this->sqlStatement = $sqlStatement;
$this->metadata = $metadata;
public function __construct(
protected $personId,
/**
* the FQDN class name as recorded in doctrine.
*/
protected $entity,
/**
* the sql statement.
*/
protected $sqlStatement,
/**
* an array of key value data to describe the movement.
*/
protected $metadata = []
) {
}
/**

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Actions\Remove\Handler;
use Chill\PersonBundle\Actions\Remove\PersonMoveSqlHandlerInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriodParticipation;
use Chill\PersonBundle\Entity\Person;
class PersonMoveAccompanyingPeriodParticipationHandler implements PersonMoveSqlHandlerInterface
{
public function supports(string $className, string $field): bool
{
return AccompanyingPeriodParticipation::class === $className;
}
public function getSqls(string $className, string $field, Person $from, Person $to): array
{
$insertSql = sprintf(<<<'SQL'
INSERT INTO chill_person_accompanying_period_participation (person_id, accompanyingperiod_id, id, startdate, enddate)
SELECT %d, accompanyingperiod_id, nextval('chill_person_accompanying_period_participation_id_seq'), startdate, enddate
FROM chill_person_accompanying_period_participation cpapp
WHERE person_id = %d
AND NOT EXISTS (
SELECT 1 FROM chill_person_accompanying_period_participation cpapp2
WHERE
person_id = %d
AND (cpapp.startdate, COALESCE(cpapp.enddate, 'infinity'::date)) OVERLAPS (cpapp2.startdate, COALESCE(cpapp2.enddate, 'infinity'::date))
);
SQL, $to->getId(), $from->getId(), $to->getId());
$deleteSql = sprintf(<<<'SQL'
DELETE FROM chill_person_accompanying_period_participation WHERE person_id = %d;
SQL, $from->getId());
return [$insertSql, $deleteSql];
}
}

View File

@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Actions\Remove\Handler;
use Chill\PersonBundle\Actions\Remove\PersonMoveSqlHandlerInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Repository\Person\PersonCenterHistoryRepository;
class PersonMoveCenterHistoryHandler implements PersonMoveSqlHandlerInterface
{
public function __construct(
private readonly PersonCenterHistoryRepository $centerHistoryRepository,
) {
}
public function supports(string $className, string $field): bool
{
return Person\PersonCenterHistory::class === $className;
}
public function getSqls(string $className, string $field, Person $from, Person $to): array
{
$sqlStatements = [];
$oldestDateA = null;
$oldestDateB = null;
$oldestCenterHistoryB = null;
$oldestCenterHistoryA = null;
$centerHistoriesA = $this->centerHistoryRepository->findBy(['person' => $from]);
foreach ($centerHistoriesA as $ch) {
if (null === $oldestDateA || ($ch->getStartDate() < $oldestDateA)) {
$oldestDateA = $ch->getStartDate();
$oldestCenterHistoryA = $ch;
}
}
$centerHistoriesB = $this->centerHistoryRepository->findBy(['person' => $to]);
foreach ($centerHistoriesB as $ch) {
if (null === $oldestDateB || ($ch->getStartDate() < $oldestDateB)) {
$oldestDateB = $ch->getStartDate();
$oldestCenterHistoryB = $ch;
}
}
$sqlDelete = sprintf(<<<'SQL'
DELETE FROM chill_person_person_center_history WHERE person_id = %d;
SQL, $from->getId());
$sqlStatements = [$sqlDelete];
if ((null !== $oldestDateA && null !== $oldestDateB) && $oldestDateA <= $oldestDateB) {
$sqlInsert = sprintf(<<<'SQL'
UPDATE chill_person_person_center_history SET startDate = '%s' WHERE id = %d;
SQL, $oldestDateA->format('Y-m-d'), $oldestCenterHistoryB->getId());
$sqlStatements = [$sqlInsert, $sqlDelete];
}
return $sqlStatements;
}
}

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Actions\Remove\Handler;
use Chill\PersonBundle\Actions\Remove\PersonMoveSqlHandlerInterface;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Entity\Person;
class PersonMoveHouseholdHandler implements PersonMoveSqlHandlerInterface
{
public function supports(string $className, string $field): bool
{
return HouseholdMember::class === $className;
}
public function getSqls(string $className, string $field, Person $from, Person $to): array
{
$sqlInsert = sprintf(<<<'SQL'
INSERT INTO chill_person_household_members (id, person_id, household_id, startdate, enddate, comment, sharedhousehold, position_id, holder)
SELECT nextval('chill_person_household_members_id_seq'), %d, household_id, startdate, enddate, comment, sharedhousehold, position_id, holder
FROM chill_person_household_members cphm
WHERE person_id = %d
AND NOT EXISTS (
SELECT 1 FROM chill_person_household_members cphm_inner
WHERE
person_id = %d
AND daterange(cphm.startdate, cphm.enddate) && daterange(cphm_inner.startdate, cphm_inner.enddate)
);
SQL, $to->getId(), $from->getId(), $to->getId());
$deleteSql = sprintf(<<<'SQL'
DELETE FROM chill_person_household_members WHERE person_id = %d;
SQL, $from->getId());
return [$sqlInsert, $deleteSql];
}
}

View File

@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Actions\Remove\Handler;
use Chill\PersonBundle\Actions\Remove\PersonMoveSqlHandlerInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relationship;
class PersonMoveRelationHandler implements PersonMoveSqlHandlerInterface
{
public function supports(string $className, string $field): bool
{
return Relationship::class === $className;
}
public function getSqls(string $className, string $field, Person $from, Person $to): array
{
/* Insert sql statement taking into account two cases.
One where the person is the fromperson and another where the person is the toperson in the relationship.*/
$insertSql = sprintf(<<<'SQL'
INSERT INTO chill_person_relationships (id, relation_id, reverse, createdat, createdby_id, fromperson_id, toperson_id)
SELECT nextval('chill_person_relationships_id_seq'), relation_id, reverse, createdat, createdby_id,
CASE
WHEN cpr.fromperson_id = %d THEN %d
ELSE cpr.fromperson_id
END as fromperson,
CASE
WHEN cpr.toperson_id = %d THEN %d
ELSE cpr.toperson_id
END as toperson
FROM chill_person_relationships cpr
WHERE fromperson_id = %d OR toperson_id = %d
AND NOT EXISTS (
SELECT 1 FROM chill_person_relationships cpr2
WHERE
cpr2.fromperson_id = %d AND cpr2.toperson_id = %d
OR cpr2.fromperson_id = %d AND cpr2.toperson_id = %d
);
SQL, $from->getId(), $to->getId(), $from->getId(), $to->getId(), $from->getId(), $from->getId(), $to->getId(), $from->getId(), $from->getId(), $to->getId());
$deleteSql = [
sprintf('DELETE FROM chill_person_relationships WHERE fromperson_id = %d', $from->getId()),
sprintf('DELETE FROM chill_person_relationships WHERE toperson_id = %d', $from->getId()),
];
return [$insertSql, ...$deleteSql];
}
}

View File

@@ -13,8 +13,6 @@ namespace Chill\PersonBundle\Actions\Remove;
use Chill\PersonBundle\Actions\ActionEvent;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriodParticipation;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Entity\Household\PersonHouseholdAddress;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relationship;
@@ -22,10 +20,6 @@ use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use function array_merge;
use function implode;
use function in_array;
/**
* Move or delete entities associated to a person to a new one, and delete the
* old person. The data associated to a person (birthdate, name, ...) are left
@@ -35,22 +29,11 @@ use function in_array;
*/
class PersonMove
{
/**
* @var EntityManagerInterface
*/
protected $em;
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
public function __construct(
EntityManagerInterface $em,
EventDispatcherInterface $eventDispatcher
private readonly EntityManagerInterface $em,
private readonly PersonMoveManager $personMoveManager,
private readonly EventDispatcherInterface $eventDispatcher
) {
$this->em = $em;
$this->eventDispatcher = $eventDispatcher;
}
/**
@@ -80,7 +63,7 @@ class PersonMove
public function getSQL(Person $from, Person $to, array $deleteEntities = [])
{
$sqls = [];
$toDelete = array_merge($deleteEntities, $this->getDeleteEntities());
$toDelete = \array_merge($deleteEntities, $this->getDeleteEntities());
foreach ($this->em->getMetadataFactory()->getAllMetadata() as $metadata) {
if ($metadata->isMappedSuperclass) {
@@ -88,11 +71,17 @@ class PersonMove
}
foreach ($metadata->getAssociationMappings() as $field => $mapping) {
if (in_array($mapping['sourceEntity'], $this->getIgnoredEntities(), true)) {
if ($this->personMoveManager->hasHandler($metadata->getName(), $field)) {
$sqls = \array_merge($sqls, $this->personMoveManager->getSqls($metadata->getName(), $field, $from, $to));
continue;
}
if (\in_array($mapping['sourceEntity'], $this->getIgnoredEntities(), true)) {
continue;
}
if (Person::class === $mapping['targetEntity'] and true === $mapping['isOwningSide']) {
if (in_array($mapping['sourceEntity'], $toDelete, true)) {
if (\in_array($mapping['sourceEntity'], $toDelete, true)) {
$sql = $this->createDeleteSQL($metadata, $from, $field);
$event = new ActionEvent(
$from->getId(),
@@ -100,26 +89,18 @@ class PersonMove
$sql,
['to' => $to->getId(), 'original_action' => 'move']
);
$this->eventDispatcher->dispatch(ActionEvent::DELETE, $event);
$this->eventDispatcher->dispatch($event, ActionEvent::DELETE);
$sqls = \array_merge($sqls, $event->getPreSql(), [$event->getSqlStatement()], $event->getPostSql());
} else {
$sql = $this->createMoveSQL($metadata, $from, $to, $field);
$event = new ActionEvent(
$from->getId(),
$metadata->getName(),
$sql,
['to' => $to->getId(), 'original_action' => 'move']
);
$this->eventDispatcher->dispatch(ActionEvent::MOVE, $event);
$sqls = \array_merge($sqls, $this->createMoveSQLs($metadata, $from, $to, $field));
}
$sqls = array_merge($sqls, $event->getPreSql(), [$event->getSqlStatement()], $event->getPostSql());
}
}
}
$personMetadata = $this->em->getClassMetadata(Person::class);
$sqls[] = sprintf(
'DELETE FROM %s WHERE id = %d',
'DELETE FROM %s WHERE id = %d;',
$this->getTableName($personMetadata),
$from->getId()
);
@@ -133,18 +114,24 @@ class PersonMove
$conditions = [];
foreach ($mapping['joinColumns'] as $columns) {
$conditions[] = sprintf('%s = %d', $columns['name'], $from->getId());
if (array_key_exists('joinTable', $mapping)) {
foreach ($mapping['joinTable']['joinColumns'] as $columns) {
$conditions[] = sprintf('%s = %d', $columns['referencedColumnName'], $from->getId());
}
} elseif (array_key_exists('joinColumns', $mapping)) {
foreach ($mapping['joinColumns'] as $columns) {
$conditions[] = sprintf('%s = %d', $columns['name'], $from->getId());
}
}
return sprintf(
'DELETE FROM %s WHERE %s',
'DELETE FROM %s WHERE %s;',
$this->getTableName($metadata),
implode(' AND ', $conditions)
\implode(' AND ', $conditions)
);
}
private function createMoveSQL(ClassMetadata $metadata, Person $from, Person $to, $field): string
private function createMoveSQLs($metadata, Person $from, Person $to, $field): array
{
$mapping = $metadata->getAssociationMapping($field);
@@ -154,8 +141,28 @@ class PersonMove
$tableName = '';
if (array_key_exists('joinTable', $mapping)) {
$tableName = (null !== ($mapping['joinTable']['schema'] ?? null) ? $mapping['joinTable']['schema'] . '.' : '')
. $mapping['joinTable']['name'];
// there is a join_table: we have to find conflict
$tableName = (null !== ($mapping['joinTable']['schema'] ?? null) ? $mapping['joinTable']['schema'].'.' : '')
.$mapping['joinTable']['name'];
$sqlInsert = sprintf(
'INSERT INTO %s (%s, %s) SELECT %d, %s FROM %s WHERE %s = %d ON CONFLICT DO NOTHING;',
$tableName,
$mapping['joinTable']['inverseJoinColumns'][0]['name'], // person_id
$mapping['joinTable']['joinColumns'][0]['name'], // something_else_id
$to->getId(),
$mapping['joinTable']['joinColumns'][0]['name'], // something_else_id
$tableName,
$mapping['joinTable']['inverseJoinColumns'][0]['name'], // person_id
$from->getId()
);
$deleteSql = sprintf(
'DELETE FROM %s WHERE %s = %d;',
$tableName,
$mapping['joinTable']['inverseJoinColumns'][0]['name'], // person_id
$from->getId()
);
foreach ($mapping['joinTable']['inverseJoinColumns'] as $columns) {
$sets[] = sprintf('%s = %d', $columns['name'], $to->getId());
@@ -164,24 +171,28 @@ class PersonMove
foreach ($mapping['joinTable']['inverseJoinColumns'] as $columns) {
$conditions[] = sprintf('%s = %d', $columns['name'], $from->getId());
}
} elseif (array_key_exists('joinColumns', $mapping)) {
return [
$sqlInsert, $deleteSql,
];
}
if (array_key_exists('joinColumns', $mapping)) {
$tableName = $this->getTableName($metadata);
foreach ($mapping['joinColumns'] as $columns) {
$sets[] = sprintf('%s = %d', $columns['name'], $to->getId());
}
foreach ($mapping['joinColumns'] as $columns) {
$conditions[] = sprintf('%s = %d', $columns['name'], $from->getId());
}
}
return sprintf(
'UPDATE %s SET %s WHERE %s',
return [sprintf(
'UPDATE %s SET %s WHERE %s;',
$tableName,
implode(' ', $sets),
implode(' AND ', $conditions)
);
\implode(' ', $sets),
\implode(' AND ', $conditions)
)];
}
/**
@@ -191,11 +202,8 @@ class PersonMove
private function getDeleteEntities(): array
{
return [
Person\PersonCenterHistory::class,
HouseholdMember::class,
AccompanyingPeriodParticipation::class,
AccompanyingPeriod\AccompanyingPeriodWork::class,
Relationship::class
Relationship::class,
];
}
@@ -215,6 +223,6 @@ class PersonMove
{
return empty($metadata->getSchemaName()) ?
$metadata->getTableName() :
$metadata->getSchemaName() . '.' . $metadata->getTableName();
$metadata->getSchemaName().'.'.$metadata->getTableName();
}
}

View File

@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Actions\Remove;
use Chill\PersonBundle\Entity\Person;
class PersonMoveManager
{
public function __construct(
/**
* @var iterable<PersonMoveSqlHandlerInterface>
*/
private readonly iterable $handlers,
) {
}
/**
* @param class-string $className
*/
public function hasHandler(string $className, string $field): bool
{
foreach ($this->handlers as $handler) {
if ($handler->supports($className, $field)) {
return true;
}
}
return false;
}
/**
* @param class-string $className
*
* @return array<string>
*/
public function getSqls(string $className, string $field, Person $from, Person $to): array
{
foreach ($this->handlers as $handler) {
if ($handler->supports($className, $field)) {
return $handler->getSqls($className, $field, $from, $to);
}
}
return [];
}
}

View File

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Actions\Remove;
use Chill\PersonBundle\Entity\Person;
interface PersonMoveSqlHandlerInterface
{
/**
* @param class-string $className
*/
public function supports(string $className, string $field): bool;
/**
* @param class-string $className
*
* @return array<string>
*/
public function getSqls(string $className, string $field, Person $from, Person $to): array;
}

View File

@@ -14,10 +14,8 @@ namespace Chill\PersonBundle\CRUD\Controller;
use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\QueryBuilder;
use Exception;
use Symfony\Component\HttpFoundation\Request;
use function array_merge;
use Symfony\Component\HttpFoundation\Response;
/**
* Class EntityPersonCRUDController
@@ -67,25 +65,21 @@ class EntityPersonCRUDController extends CRUDController
}
/**
* @param mixed $entity
*
* @throws Exception
* @throws \Exception
*/
protected function generateTemplateParameter(string $action, $entity, Request $request, array $defaultTemplateParameters = []): array
{
$person = $this->getPerson($request);
if (null === $person) {
throw new Exception('the `person_id` parameter is not set in the query. '
. 'You should set it or override the current method to allow another '
. 'behaviour: ' . __METHOD__);
throw new \Exception('the `person_id` parameter is not set in the query. You should set it or override the current method to allow another behaviour: '.__METHOD__);
}
return parent::generateTemplateParameter(
$action,
$entity,
$request,
array_merge(['person' => $person], $defaultTemplateParameters)
\array_merge(['person' => $person], $defaultTemplateParameters)
);
}
@@ -121,7 +115,6 @@ class EntityPersonCRUDController extends CRUDController
/**
* @param string $action
* @param mixed $entity
*
* @return string
*/
@@ -131,58 +124,35 @@ class EntityPersonCRUDController extends CRUDController
return $this->getActionConfig($action)['template'];
}
switch ($action) {
case 'new':
return '@ChillPerson/CRUD/new.html.twig';
case 'edit':
return '@ChillPerson/CRUD/edit.html.twig';
case 'view':
return '@ChillPerson/CRUD/view.html.twig';
case 'delete':
return '@ChillPerson/CRUD/delete.html.twig';
case 'index':
return '@ChillPerson/CRUD/index.html.twig';
default:
return parent::getTemplateFor($action, $entity, $request);
}
return match ($action) {
'new' => '@ChillPerson/CRUD/new.html.twig',
'edit' => '@ChillPerson/CRUD/edit.html.twig',
'view' => '@ChillPerson/CRUD/view.html.twig',
'delete' => '@ChillPerson/CRUD/delete.html.twig',
'index' => '@ChillPerson/CRUD/index.html.twig',
default => parent::getTemplateFor($action, $entity, $request),
};
}
/**
* @param mixed $entity
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
protected function onBeforeRedirectAfterSubmission(string $action, $entity, \Symfony\Component\Form\FormInterface $form, Request $request)
protected function onBeforeRedirectAfterSubmission(string $action, $entity, \Symfony\Component\Form\FormInterface $form, Request $request): ?Response
{
$next = $request->request->get('submit', 'save-and-close');
switch ($next) {
case 'save-and-close':
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_index', [
'person_id' => $this->getPerson($request)->getId(),
]);
case 'save-and-new':
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_new', [
'person_id' => $this->getPerson($request)->getId(),
]);
case 'new':
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_view', [
'id' => $entity->getId(),
'person_id' => $this->getPerson($request)->getId(),
]);
default:
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_view', [
'id' => $entity->getId(),
'person_id' => $this->getPerson($request)->getId(),
]);
}
return match ($next) {
'save-and-close' => $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_index', [
'person_id' => $this->getPerson($request)->getId(),
]),
'save-and-new' => $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_new', [
'person_id' => $this->getPerson($request)->getId(),
]),
'new' => $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_view', [
'id' => $entity->getId(),
'person_id' => $this->getPerson($request)->getId(),
]),
default => $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_view', [
'id' => $entity->getId(),
'person_id' => $this->getPerson($request)->getId(),
]),
};
}
}

View File

@@ -11,10 +11,8 @@ declare(strict_types=1);
namespace Chill\PersonBundle\CRUD\Controller;
use BadMethodCallException;
use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\PersonBundle\Entity\Person;
use LogicException;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
@@ -22,9 +20,9 @@ use Symfony\Component\HttpFoundation\Response;
class OneToOneEntityPersonCRUDController extends CRUDController
{
protected function generateRedirectOnCreateRoute($action, Request $request, $entity)
protected function generateRedirectOnCreateRoute($action, Request $request, $entity): string
{
throw new BadMethodCallException('Not implemented yet.');
throw new \BadMethodCallException('Not implemented yet.');
}
protected function getEntity($action, $id, Request $request): ?object
@@ -50,21 +48,12 @@ class OneToOneEntityPersonCRUDController extends CRUDController
return $this->crudConfig[$action]['template'];
}
switch ($action) {
case 'new':
return '@ChillPerson/CRUD/new.html.twig';
case 'edit':
return '@ChillPerson/CRUD/edit.html.twig';
case 'index':
return '@ChillPerson/CRUD/index.html.twig';
default:
throw new LogicException("the view for action {$action} is not "
. 'defined. You should override ' . __METHOD__ . ' to add this '
. 'action');
}
return match ($action) {
'new' => '@ChillPerson/CRUD/new.html.twig',
'edit' => '@ChillPerson/CRUD/edit.html.twig',
'index' => '@ChillPerson/CRUD/index.html.twig',
default => throw new \LogicException("the view for action {$action} is not ".'defined. You should override '.__METHOD__.' to add this action'),
};
}
protected function onPostFetchEntity($action, Request $request, $entity): ?Response

View File

@@ -11,7 +11,9 @@ declare(strict_types=1);
namespace Chill\PersonBundle;
use Chill\PersonBundle\Actions\Remove\PersonMoveSqlHandlerInterface;
use Chill\PersonBundle\DependencyInjection\CompilerPass\AccompanyingPeriodTimelineCompilerPass;
use Chill\PersonBundle\Export\Helper\CustomizeListPersonHelperInterface;
use Chill\PersonBundle\Service\EntityInfo\AccompanyingPeriodInfoUnionQueryPartInterface;
use Chill\PersonBundle\Widget\PersonListWidgetFactory;
use Symfony\Component\DependencyInjection\ContainerBuilder;
@@ -26,8 +28,12 @@ class ChillPersonBundle extends Bundle
$container->getExtension('chill_main')
->addWidgetFactory(new PersonListWidgetFactory());
$container->addCompilerPass(new AccompanyingPeriodTimelineCompilerPass());
$container->addCompilerPass(new AccompanyingPeriodTimelineCompilerPass(), \Symfony\Component\DependencyInjection\Compiler\PassConfig::TYPE_BEFORE_OPTIMIZATION, 0);
$container->registerForAutoconfiguration(AccompanyingPeriodInfoUnionQueryPartInterface::class)
->addTag('chill_person.accompanying_period_info_part');
$container->registerForAutoconfiguration(PersonMoveSqlHandlerInterface::class)
->addTag('chill_person.person_move_handler');
$container->registerForAutoconfiguration(CustomizeListPersonHelperInterface::class)
->addTag('chill_person.list_person_customizer');
}
}

View File

@@ -21,26 +21,14 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use function ctype_digit;
final class ChillPersonMoveCommand extends Command
{
private LoggerInterface $chillLogger;
private EntityManagerInterface $em;
private PersonMove $mover;
public function __construct(
PersonMove $mover,
EntityManagerInterface $em,
LoggerInterface $chillLogger
private readonly PersonMove $mover,
private readonly EntityManagerInterface $em,
private readonly LoggerInterface $chillLogger
) {
parent::__construct('chill:person:move');
$this->mover = $mover;
$this->em = $em;
$this->chillLogger = $chillLogger;
}
protected function buildLoggingContext(Person $from, Person $to, $deleteEntities, $sqls)
@@ -51,11 +39,11 @@ final class ChillPersonMoveCommand extends Command
];
foreach ($deleteEntities as $key => $de) {
$ctxt['delete_entity_' . $key] = $de;
$ctxt['delete_entity_'.$key] = $de;
}
foreach ($sqls as $key => $sql) {
$ctxt['sql_' . $key] = $sql;
$ctxt['sql_'.$key] = $sql;
}
return $ctxt;
@@ -73,7 +61,7 @@ final class ChillPersonMoveCommand extends Command
->addOption('delete-entity', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'entity to delete', []);
}
protected function execute(InputInterface $input, OutputInterface $output)
protected function execute(InputInterface $input, OutputInterface $output): int
{
$repository = $this->em->getRepository(Person::class);
$from = $repository->find($input->getOption('from'));
@@ -110,6 +98,8 @@ final class ChillPersonMoveCommand extends Command
$this->chillLogger->notice('Move a person from command line succeeded', $ctxt);
}
return 0;
}
protected function interact(InputInterface $input, OutputInterface $output)
@@ -126,9 +116,8 @@ final class ChillPersonMoveCommand extends Command
}
$id = $input->getOption($name);
if (ctype_digit($id) === false) {
throw new RuntimeException("The id in \"{$name}\" field does not contains "
. "only digits: {$id}");
if (false === \ctype_digit((string) $id)) {
throw new RuntimeException("The id in \"{$name}\" field does not contains only digits: {$id}");
}
}
}

View File

@@ -11,42 +11,31 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Command;
use Chill\PersonBundle\Service\Import\ChillImporter;
use Chill\PersonBundle\Service\Import\SocialWorkMetadataInterface;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use League\Csv\Reader;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
final class ImportSocialWorkMetadata extends Command
{
protected EntityManagerInterface $em;
/**
* @var LoggerInterface
*/
protected ChillImporter $importer;
public function __construct(
SocialWorkMetadataInterface $socialWorkMetadata
protected SocialWorkMetadataInterface $importer
) {
parent::__construct('chill:person:import-socialwork');
$this->importer = $socialWorkMetadata;
}
protected function configure()
{
$description = 'Imports a structured table containing social issues, social actions, objectives, results and evaluations.';
$help = 'File to csv format, no headers, semi-colon as delimiter, datas sorted by alphabetical order, column after column.'. PHP_EOL
. 'Columns are: social issues parent, social issues child, social actions parent, social actions child, goals, results, evaluations.'. PHP_EOL
. PHP_EOL
. 'See social_work_metadata.csv as example.'. PHP_EOL;
$help = 'File to csv format, no headers, semi-colon as delimiter, datas sorted by alphabetical order, column after column.'.PHP_EOL
.'Columns are: social issues parent, social issues child, social actions parent, social actions child, goals, results, evaluations.'.PHP_EOL
.PHP_EOL
.'See social_work_metadata.csv as example.'.PHP_EOL;
$this
->setName('chill:person:import-socialwork')
@@ -56,14 +45,14 @@ final class ImportSocialWorkMetadata extends Command
->setHelp($help);
}
protected function execute(InputInterface $input, OutputInterface $output)
protected function execute(InputInterface $input, OutputInterface $output): int
{
$filepath = $input->getOption('filepath');
try {
$csv = Reader::createFromPath($filepath);
} catch (Throwable $e) {
throw new Exception('Error while loading CSV.', 0, $e);
} catch (\Throwable $e) {
throw new \Exception('Error while loading CSV.', 0, $e);
}
$csv->setDelimiter(';');

View File

@@ -12,8 +12,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Command;
use Chill\PersonBundle\Service\AccompanyingPeriod\OldDraftAccompanyingPeriodRemoverInterface;
use DateInterval;
use Exception;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
@@ -22,16 +20,9 @@ use Symfony\Component\Console\Output\OutputInterface;
class RemoveOldDraftAccompanyingPeriodCommand extends Command
{
private LoggerInterface $logger;
private OldDraftAccompanyingPeriodRemoverInterface $remover;
public function __construct(LoggerInterface $logger, OldDraftAccompanyingPeriodRemoverInterface $remover)
public function __construct(private readonly LoggerInterface $logger, private readonly OldDraftAccompanyingPeriodRemoverInterface $remover)
{
parent::__construct('chill:person:remove-old-draft-period');
$this->logger = $logger;
$this->remover = $remover;
}
protected function configure(): void
@@ -43,21 +34,21 @@ class RemoveOldDraftAccompanyingPeriodCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->logger->info('[' . $this->getName() . '] started', [
$this->logger->info('['.$this->getName().'] started', [
'interval' => $input->getArgument('interval'),
]);
try {
$interval = new DateInterval($input->getArgument('interval'));
} catch (Exception $e) {
$this->logger->error('[' . $this->getName() . '] bad interval');
$interval = new \DateInterval($input->getArgument('interval'));
} catch (\Exception $e) {
$this->logger->error('['.$this->getName().'] bad interval');
throw $e;
}
$this->remover->remove($interval);
$this->logger->info('[' . $this->getName() . '] end of command');
$this->logger->info('['.$this->getName().'] end of command');
return 0;
}

View File

@@ -17,15 +17,14 @@ namespace Chill\PersonBundle\Config;
class ConfigPersonAltNamesHelper
{
/**
* the raw config, directly from the container parameter.
*
* @var array
* @param mixed[] $config
*/
private $config = [];
public function __construct($config)
{
$this->config = $config;
public function __construct(
/**
* the raw config, directly from the container parameter.
*/
private $config
) {
}
/**
@@ -42,11 +41,11 @@ class ConfigPersonAltNamesHelper
$cur = reset($labels);
while ($cur) {
if (key($labels) === 'lang') {
if ('lang' === key($labels)) {
$lang = current($labels);
}
if (key($labels) === 'label') {
if ('label' === key($labels)) {
$label = current($labels);
}

View File

@@ -29,8 +29,6 @@ use Chill\PersonBundle\Repository\AccompanyingPeriodACLAwareRepository;
use Chill\PersonBundle\Repository\AccompanyingPeriodRepository;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use DateInterval;
use DateTimeImmutable;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -43,40 +41,13 @@ use Symfony\Component\Serializer\Exception\RuntimeException;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Workflow\Registry;
use function array_values;
use function count;
final class AccompanyingCourseApiController extends ApiController
{
private AccompanyingPeriodACLAwareRepository $accompanyingPeriodACLAwareRepository;
private AccompanyingPeriodRepository $accompanyingPeriodRepository;
private EventDispatcherInterface $eventDispatcher;
private ReferralsSuggestionInterface $referralAvailable;
private Registry $registry;
private ValidatorInterface $validator;
public function __construct(
AccompanyingPeriodRepository $accompanyingPeriodRepository,
AccompanyingPeriodACLAwareRepository $accompanyingPeriodACLAwareRepository,
EventDispatcherInterface $eventDispatcher,
ReferralsSuggestionInterface $referralAvailable,
Registry $registry,
ValidatorInterface $validator
) {
$this->accompanyingPeriodRepository = $accompanyingPeriodRepository;
$this->accompanyingPeriodACLAwareRepository = $accompanyingPeriodACLAwareRepository;
$this->eventDispatcher = $eventDispatcher;
$this->referralAvailable = $referralAvailable;
$this->registry = $registry;
$this->validator = $validator;
public function __construct(private readonly AccompanyingPeriodRepository $accompanyingPeriodRepository, private readonly AccompanyingPeriodACLAwareRepository $accompanyingPeriodACLAwareRepository, private readonly EventDispatcherInterface $eventDispatcher, private readonly ReferralsSuggestionInterface $referralAvailable, private readonly Registry $registry, private readonly ValidatorInterface $validator)
{
}
public function commentApi($id, Request $request, string $_format): Response
@@ -96,7 +67,7 @@ final class AccompanyingCourseApiController extends ApiController
// throw new BadRequestException('It is not possible to confirm this period');
$errors = $this->validator->validate($accompanyingPeriod, null, [$accompanyingPeriod::STEP_CONFIRMED]);
if (count($errors) > 0) {
if (\count($errors) > 0) {
return $this->json($errors, 422);
}
}
@@ -122,7 +93,7 @@ final class AccompanyingCourseApiController extends ApiController
throw new AccessDeniedException();
}
$since = (new DateTimeImmutable('now'))->sub(new DateInterval('P15D'));
$since = (new \DateTimeImmutable('now'))->sub(new \DateInterval('P15D'));
$total = $this->accompanyingPeriodRepository->countByRecentUserHistory($user, $since);
@@ -172,7 +143,7 @@ final class AccompanyingCourseApiController extends ApiController
fn (AccompanyingPeriod $period) => $this->isGranted(AccompanyingPeriodVoter::SEE, $period)
);
return $this->json(array_values($accompanyingPeriodsChecked), Response::HTTP_OK, [], ['groups' => ['read']]);
return $this->json(\array_values($accompanyingPeriodsChecked), Response::HTTP_OK, [], ['groups' => ['read']]);
}
public function participationApi($id, Request $request, $_format)
@@ -190,20 +161,11 @@ final class AccompanyingCourseApiController extends ApiController
//
$this->onPostCheckACL('participation', $request, $_format, $accompanyingPeriod);
switch ($request->getMethod()) {
case Request::METHOD_POST:
$participation = $accompanyingPeriod->createParticipationFor($person);
break;
case Request::METHOD_DELETE:
$participation = $accompanyingPeriod->closeParticipationFor($person);
break;
default:
throw new BadRequestHttpException('This method is not supported');
}
$participation = match ($request->getMethod()) {
Request::METHOD_POST => $accompanyingPeriod->createParticipationFor($person),
Request::METHOD_DELETE => $accompanyingPeriod->closeParticipationFor($person),
default => throw new BadRequestHttpException('This method is not supported'),
};
$errors = $this->validator->validate($accompanyingPeriod);
@@ -319,13 +281,12 @@ final class AccompanyingCourseApiController extends ApiController
/**
* @Route("/api/1.0/person/accompanying-course/{id}/confidential.json", name="chill_api_person_accompanying_period_confidential")
* @ParamConverter("accompanyingCourse", options={"id": "id"})
*
* @param mixed $id
* @ParamConverter("accompanyingCourse", options={"id": "id"})
*/
public function toggleConfidentialApi(AccompanyingPeriod $accompanyingCourse, $id, Request $request)
public function toggleConfidentialApi(AccompanyingPeriod $accompanyingCourse, mixed $id, Request $request)
{
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$this->denyAccessUnlessGranted(AccompanyingPeriodVoter::TOGGLE_CONFIDENTIAL, $accompanyingCourse);
$accompanyingCourse->setConfidential(!$accompanyingCourse->isConfidential());
@@ -338,14 +299,15 @@ final class AccompanyingCourseApiController extends ApiController
/**
* @Route("/api/1.0/person/accompanying-course/{id}/intensity.json", name="chill_api_person_accompanying_period_intensity")
*
* @ParamConverter("accompanyingCourse", options={"id": "id"})
*/
public function toggleIntensityApi(AccompanyingPeriod $accompanyingCourse, Request $request)
{
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$this->denyAccessUnlessGranted(AccompanyingPeriodVoter::TOGGLE_INTENSITY, $accompanyingCourse);
$status = $accompanyingCourse->getIntensity() === 'regular' ? 'occasional' : 'regular';
$status = 'regular' === $accompanyingCourse->getIntensity() ? 'occasional' : 'regular';
$accompanyingCourse->setIntensity($status);
$this->getDoctrine()->getManager()->flush();
}
@@ -370,11 +332,11 @@ final class AccompanyingCourseApiController extends ApiController
protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response
{
$this->eventDispatcher->dispatch(
AccompanyingPeriodPrivacyEvent::ACCOMPANYING_PERIOD_PRIVACY_EVENT,
new AccompanyingPeriodPrivacyEvent($entity, [
'action' => $action,
'request' => $request->getMethod(),
])
]),
AccompanyingPeriodPrivacyEvent::ACCOMPANYING_PERIOD_PRIVACY_EVENT
);
return null;

View File

@@ -16,7 +16,6 @@ use Chill\PersonBundle\Form\AccompanyingCourseCommentType;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodCommentVoter;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\FormType;
@@ -26,32 +25,20 @@ use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
class AccompanyingCourseCommentController extends AbstractController
{
private EntityManagerInterface $entityManager;
private FormFactoryInterface $formFactory;
private TranslatorInterface $translator;
public function __construct(
EntityManagerInterface $entityManager,
FormFactoryInterface $formFactory,
TranslatorInterface $translator
) {
$this->entityManager = $entityManager;
$this->formFactory = $formFactory;
$this->translator = $translator;
public function __construct(private readonly EntityManagerInterface $entityManager, private readonly FormFactoryInterface $formFactory, private readonly TranslatorInterface $translator)
{
}
/**
* Page of comments in Accompanying Course section.
*
* @Route("/{_locale}/parcours/{accompanying_period_id}/comments", name="chill_person_accompanying_period_comment_list")
*
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function commentAction(AccompanyingPeriod $accompanyingCourse, Request $request): Response
@@ -80,13 +67,13 @@ class AccompanyingCourseCommentController extends AbstractController
}
if (!isset($editForm)) {
throw new NotFoundHttpException('comment with id ' . $request->query->getInt('edit') . ' is not found');
throw new NotFoundHttpException('comment with id '.$request->query->getInt('edit').' is not found');
}
if (isset($commentEdited)) {
$this->denyAccessUnlessGranted(AccompanyingPeriodCommentVoter::EDIT, $commentEdited);
} else {
throw new LogicException('at this step, commentEdited should be set');
throw new \LogicException('at this step, commentEdited should be set');
}
$editForm->handleRequest($request);

View File

@@ -19,7 +19,6 @@ use Chill\PersonBundle\Form\AccompanyingCourseType;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@@ -33,44 +32,18 @@ use Symfony\Component\Workflow\Registry;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_slice;
use function is_array;
/**
* Class AccompanyingCourseController.
*/
class AccompanyingCourseController extends Controller
class AccompanyingCourseController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
protected EventDispatcherInterface $dispatcher;
protected SerializerInterface $serializer;
protected ValidatorInterface $validator;
private Registry $registry;
private TranslatorInterface $translator;
private AccompanyingPeriodWorkRepository $workRepository;
public function __construct(
SerializerInterface $serializer,
EventDispatcherInterface $dispatcher,
ValidatorInterface $validator,
AccompanyingPeriodWorkRepository $workRepository,
Registry $registry,
TranslatorInterface $translator
) {
$this->serializer = $serializer;
$this->dispatcher = $dispatcher;
$this->validator = $validator;
$this->workRepository = $workRepository;
$this->registry = $registry;
$this->translator = $translator;
public function __construct(protected SerializerInterface $serializer, protected EventDispatcherInterface $dispatcher, protected ValidatorInterface $validator, private readonly AccompanyingPeriodWorkRepository $workRepository, private readonly Registry $registry, private readonly TranslatorInterface $translator)
{
}
/**
* @Route("/{_locale}/parcours/{accompanying_period_id}/close", name="chill_person_accompanying_course_close")
*
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function closeAction(AccompanyingPeriod $accompanyingCourse, Request $request): Response
@@ -89,7 +62,7 @@ class AccompanyingCourseController extends Controller
$workflow = $this->registry->get($accompanyingCourse);
if ($workflow->can($accompanyingCourse, 'close')) {
$workflow->apply($accompanyingCourse, 'close');
$workflow->apply($accompanyingCourse, 'close', ['closing_motive' => $form['closingMotive']->getData()]);
$em->flush();
@@ -102,7 +75,7 @@ class AccompanyingCourseController extends Controller
$this->addFlash('error', $this->translator->trans('It is not possible to close this course'));
foreach ($errors as $e) {
/** @var ConstraintViolationInterface $e */
/* @var ConstraintViolationInterface $e */
$this->addFlash('error', $e->getMessage());
}
}
@@ -117,6 +90,7 @@ class AccompanyingCourseController extends Controller
* Delete page of Accompanying Course section.
*
* @Route("/{_locale}/parcours/{accompanying_period_id}/delete", name="chill_person_accompanying_course_delete")
*
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function deleteAction(Request $request, AccompanyingPeriod $accompanyingCourse)
@@ -134,14 +108,14 @@ class AccompanyingCourseController extends Controller
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
if ($request->getMethod() === Request::METHOD_DELETE) {
if (Request::METHOD_DELETE === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$em->remove($accompanyingCourse);
$em->flush();
$this->addFlash('success', $this->get('translator')
$this->addFlash('success', $this->translator
->trans('The accompanying course has been successfully removed.'));
if (null !== $person_id) {
@@ -173,6 +147,7 @@ class AccompanyingCourseController extends Controller
* the page edit all blocks managed by vuejs component
*
* @Route("/{_locale}/parcours/{accompanying_period_id}/edit", name="chill_person_accompanying_course_edit")
*
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function editAction(AccompanyingPeriod $accompanyingCourse): Response
@@ -190,6 +165,7 @@ class AccompanyingCourseController extends Controller
* the page show anti chronologic history with all actions, title of page is 'Accompanying Course History'
*
* @Route("/{_locale}/parcours/{accompanying_period_id}/history", name="chill_person_accompanying_course_history")
*
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function historyAction(AccompanyingPeriod $accompanyingCourse): Response
@@ -205,6 +181,7 @@ class AccompanyingCourseController extends Controller
* Homepage of Accompanying Course section.
*
* @Route("/{_locale}/parcours/{accompanying_period_id}", name="chill_person_accompanying_course_index")
*
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function indexAction(AccompanyingPeriod $accompanyingCourse): Response
@@ -226,7 +203,7 @@ class AccompanyingCourseController extends Controller
['date' => 'DESC', 'id' => 'DESC'],
);
$activities = array_slice($activities, 0, 3);
$activities = \array_slice($activities, 0, 3);
$works = $this->workRepository->findByAccompanyingPeriod(
$accompanyingCourse,
@@ -254,7 +231,7 @@ class AccompanyingCourseController extends Controller
if ($request->query->has('person_id')) {
$personIds = $request->query->get('person_id');
if (false === is_array($personIds)) {
if (false === \is_array($personIds)) {
throw new BadRequestHttpException('person_id parameter should be an array');
}
@@ -316,6 +293,7 @@ class AccompanyingCourseController extends Controller
/**
* @Route("/{_locale}/parcours/{accompanying_period_id}/open", name="chill_person_accompanying_course_reopen")
*
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/
public function reOpenAction(AccompanyingPeriod $accompanyingCourse, Request $request): Response

View File

@@ -15,19 +15,14 @@ use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\MainBundle\Serializer\Model\Counter;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use DateInterval;
use DateTimeImmutable;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class AccompanyingCourseWorkApiController extends ApiController
{
private AccompanyingPeriodWorkRepository $accompanyingPeriodWorkRepository;
public function __construct(AccompanyingPeriodWorkRepository $accompanyingPeriodWorkRepository)
public function __construct(private readonly AccompanyingPeriodWorkRepository $accompanyingPeriodWorkRepository)
{
$this->accompanyingPeriodWorkRepository = $accompanyingPeriodWorkRepository;
}
/**
@@ -35,10 +30,10 @@ class AccompanyingCourseWorkApiController extends ApiController
*/
public function myWorksNearEndDate(Request $request): JsonResponse
{
$since = (new DateTimeImmutable('now'))
->sub(new DateInterval('P' . $request->query->getInt('since', 15) . 'D'));
$until = (new DateTimeImmutable('now'))
->add(new DateInterval('P' . $request->query->getInt('since', 15) . 'D'));
$since = (new \DateTimeImmutable('now'))
->sub(new \DateInterval('P'.$request->query->getInt('since', 15).'D'));
$until = (new \DateTimeImmutable('now'))
->add(new \DateInterval('P'.$request->query->getInt('since', 15).'D'));
$total = $this->accompanyingPeriodWorkRepository
->countNearEndDateByUser($this->getUser(), $since, $until);

View File

@@ -11,45 +11,38 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Controller;
use Chill\DocStoreBundle\Serializer\Normalizer\StoredObjectNormalizer;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Chill\MainBundle\Templating\Listing\FilterOrderHelperFactoryInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWork;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodWorkVoter;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class AccompanyingCourseWorkController extends AbstractController
final class AccompanyingCourseWorkController extends AbstractController
{
private LoggerInterface $chillLogger;
private PaginatorFactory $paginator;
private SerializerInterface $serializer;
private TranslatorInterface $trans;
private AccompanyingPeriodWorkRepository $workRepository;
public function __construct(
TranslatorInterface $trans,
SerializerInterface $serializer,
AccompanyingPeriodWorkRepository $workRepository,
PaginatorFactory $paginator,
LoggerInterface $chillLogger
private readonly TranslatorInterface $trans,
private readonly SerializerInterface $serializer,
private readonly AccompanyingPeriodWorkRepository $workRepository,
private readonly PaginatorFactory $paginator,
private readonly LoggerInterface $chillLogger,
private readonly TranslatableStringHelperInterface $translatableStringHelper,
private readonly FilterOrderHelperFactoryInterface $filterOrderHelperFactory
) {
$this->trans = $trans;
$this->serializer = $serializer;
$this->workRepository = $workRepository;
$this->paginator = $paginator;
$this->chillLogger = $chillLogger;
}
/**
@@ -63,11 +56,11 @@ class AccompanyingCourseWorkController extends AbstractController
{
$this->denyAccessUnlessGranted(AccompanyingPeriodWorkVoter::CREATE, $period);
if ($period->getSocialIssues()->count() === 0) {
if (0 === $period->getSocialIssues()->count()) {
$this->addFlash(
'error',
$this->trans->trans(
'accompanying_work.You must add at least ' .
'accompanying_work.You must add at least '.
'one social issue on accompanying period'
)
);
@@ -100,7 +93,7 @@ class AccompanyingCourseWorkController extends AbstractController
$form = $this->createDeleteForm($work->getId());
if ($request->getMethod() === Request::METHOD_DELETE) {
if (Request::METHOD_DELETE === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -142,7 +135,7 @@ class AccompanyingCourseWorkController extends AbstractController
{
$this->denyAccessUnlessGranted(AccompanyingPeriodWorkVoter::UPDATE, $work);
$json = $this->serializer->normalize($work, 'json', ['groups' => ['read']]);
$json = $this->serializer->normalize($work, 'json', ['groups' => ['read', StoredObjectNormalizer::ADD_DAV_EDIT_LINK_CONTEXT]]);
return $this->render('@ChillPerson/AccompanyingCourseWork/edit.html.twig', [
'accompanyingCourse' => $work->getAccompanyingPeriod(),
@@ -162,11 +155,21 @@ class AccompanyingCourseWorkController extends AbstractController
{
$this->denyAccessUnlessGranted(AccompanyingPeriodWorkVoter::SEE, $period);
$filter = $this->buildFilterOrder($period);
$filterData = [
'types' => $filter->hasEntityChoice('typesFilter') ? $filter->getEntityChoiceData('typesFilter') : [],
'before' => $filter->getDateRangeData('dateFilter')['to'],
'after' => $filter->getDateRangeData('dateFilter')['from'],
'user' => $filter->getUserPickerData('userFilter'),
];
$totalItems = $this->workRepository->countByAccompanyingPeriod($period);
$paginator = $this->paginator->create($totalItems);
$works = $this->workRepository->findByAccompanyingPeriodOpenFirst(
$period,
$filterData,
$paginator->getItemsPerPage(),
$paginator->getCurrentPageFirstItemNumber()
);
@@ -175,6 +178,7 @@ class AccompanyingCourseWorkController extends AbstractController
'accompanyingCourse' => $period,
'works' => $works,
'paginator' => $paginator,
'filter' => $filter,
]);
}
@@ -199,7 +203,7 @@ class AccompanyingCourseWorkController extends AbstractController
]);
}
private function createDeleteForm(int $id): Form
private function createDeleteForm(int $id): FormInterface
{
$params = [];
$params['id'] = $id;
@@ -210,4 +214,26 @@ class AccompanyingCourseWorkController extends AbstractController
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
}
private function buildFilterOrder($associatedPeriod): FilterOrderHelper
{
$filterBuilder = $this->filterOrderHelperFactory->create(self::class);
$types = $this->workRepository->findActionTypeByPeriod($associatedPeriod);
$filterBuilder
->addDateRange('dateFilter', 'accompanying_course_work.date_filter');
if (1 < count($types)) {
$filterBuilder
->addEntityChoice('typesFilter', 'accompanying_course_work.types_filter', SocialAction::class, $types, [
'choice_label' => fn (SocialAction $sa) => $this->translatableStringHelper->localize($sa->getTitle()),
]);
}
$filterBuilder
->addUserPicker('userFilter', 'accompanying_course_work.user_filter', ['required' => false])
;
return $filterBuilder->build();
}
}

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Controller;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocument;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodWorkVoter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class AccompanyingCourseWorkEvaluationDocumentController extends AbstractController
{
public function __construct(private readonly Security $security)
{
}
/**
* @Route(
* "{_locale}/person/accompanying-period/work/evaluation/document/{id}/show",
* name="chill_person_accompanying_period_work_evaluation_document_show",
* methods={"GET"}
* )
*/
public function showAccompanyingCourseWork(AccompanyingPeriodWorkEvaluationDocument $document): Response
{
$work = $document->getAccompanyingPeriodWorkEvaluation()->getAccompanyingPeriodWork();
return $this->redirectToRoute(
$this->security->isGranted(AccompanyingPeriodWorkVoter::UPDATE, $work) ?
'chill_person_accompanying_period_work_edit' : 'chill_person_accompanying_period_work_show',
[
'id' => $work->getId(),
]
);
}
}

View File

@@ -18,7 +18,6 @@ use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\PersonBundle\Repository\AccompanyingPeriodACLAwareRepositoryInterface;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use DateTime;
use Doctrine\DBAL\Exception;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@@ -27,39 +26,26 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_filter;
use function count;
/**
* Class AccompanyingPeriodController.
*/
class AccompanyingPeriodController extends AbstractController
{
protected AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository;
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @var ValidatorInterface
*/
protected $validator;
public function __construct(
AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository,
EventDispatcherInterface $eventDispatcher,
ValidatorInterface $validator
protected AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository,
private readonly EventDispatcherInterface $eventDispatcher,
private readonly ValidatorInterface $validator,
private readonly TranslatorInterface $translator
) {
$this->accompanyingPeriodACLAwareRepository = $accompanyingPeriodACLAwareRepository;
$this->eventDispatcher = $eventDispatcher;
$this->validator = $validator;
}
/**
* @throws \Exception
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/accompanying-period/close", name="chill_person_accompanying_period_close")
*/
public function closeAction(int $person_id, Request $request): Response
{
@@ -67,19 +53,17 @@ class AccompanyingPeriodController extends AbstractController
$this->denyAccessUnlessGranted(PersonVoter::UPDATE, $person, 'You are not allowed to update this person');
if ($person->isOpen() === false) {
if (false === $person->isOpen()) {
$this->get('session')->getFlashBag()
->add('error', $this->get('translator')
->add('error', $this->translator
->trans(
'Beware period is closed',
['%name%' => $person->__toString()]
));
return $this->redirect(
$this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
])
);
return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
]);
}
$current = $person->getCurrentAccompanyingPeriod();
@@ -89,41 +73,39 @@ class AccompanyingPeriodController extends AbstractController
'center' => $person->getCenter(),
]);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$person->close($current);
$errors = $this->_validatePerson($person);
if (count($errors) === 0) {
if (0 === \count($errors)) {
$this->get('session')->getFlashBag()
->add('success', $this->get('translator')
->add('success', $this->translator
->trans('An accompanying period has been closed.', [
'%name%' => $person->__toString(),
]));
$this->getDoctrine()->getManager()->flush();
return $this->redirect(
$this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
])
);
return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
]);
}
$this->get('session')->getFlashBag()
->add('error', $this->get('translator')
->add('error', $this->translator
->trans('Error! Period not closed!'));
foreach ($errors as $error) {
$this->get('session')->getFlashBag()
->add('info', $error->getMessage());
}
} else { //if form is not valid
} else { // if form is not valid
$this->get('session')->getFlashBag()
->add(
'error',
$this->get('translator')
$this->translator
->trans('Pediod closing form is not valid')
);
@@ -134,13 +116,16 @@ class AccompanyingPeriodController extends AbstractController
}
}
return $this->render('ChillPersonBundle:AccompanyingPeriod:form.html.twig', [
return $this->render('@ChillPerson/AccompanyingPeriod/form.html.twig', [
'form' => $form->createView(),
'person' => $person,
'accompanying_period' => $current,
]);
}
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/accompanying-period/create", name="chill_person_accompanying_period_create")
*/
public function createAction(int $person_id, Request $request): Response
{
$person = $this->_getPerson($person_id);
@@ -151,11 +136,11 @@ class AccompanyingPeriodController extends AbstractController
'You are not allowed to update this person'
);
$accompanyingPeriod = new AccompanyingPeriod(new DateTime('now'));
$accompanyingPeriod->setClosingDate(new DateTime('now'));
$accompanyingPeriod = new AccompanyingPeriod(new \DateTime('now'));
$accompanyingPeriod->setClosingDate(new \DateTime('now'));
$accompanyingPeriod->addPerson($person);
//or $person->addAccompanyingPeriod($accompanyingPeriod);
// or $person->addAccompanyingPeriod($accompanyingPeriod);
$form = $this->createForm(
AccompanyingPeriodType::class,
@@ -166,32 +151,30 @@ class AccompanyingPeriodController extends AbstractController
]
);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
$errors = $this->_validatePerson($person);
$flashBag = $this->get('session')->getFlashBag();
if (
$form->isValid(['Default', 'closed'])
&& count($errors) === 0
&& 0 === \count($errors)
) {
$em = $this->getDoctrine()->getManager();
$em->persist($accompanyingPeriod);
$em->flush();
$flashBag->add(
'success',
$this->get('translator')->trans(
$this->translator->trans(
'A period has been created.'
)
);
return $this->redirect(
$this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
])
);
return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
]);
}
$flashBag->add('error', $this->get('translator')
$flashBag->add('error', $this->translator
->trans('Error! Period not created!'));
foreach ($errors as $error) {
@@ -199,7 +182,7 @@ class AccompanyingPeriodController extends AbstractController
}
}
return $this->render('ChillPersonBundle:AccompanyingPeriod:form.html.twig', [
return $this->render('@ChillPerson/AccompanyingPeriod/form.html.twig', [
'form' => $form->createView(),
'person' => $person,
'accompanying_period' => $accompanyingPeriod,
@@ -208,6 +191,8 @@ class AccompanyingPeriodController extends AbstractController
/**
* @ParamConverter("person", options={"id": "person_id"})
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/accompanying-period", name="chill_person_accompanying_period_list")
*/
public function listAction(Person $person): Response
{
@@ -217,15 +202,15 @@ class AccompanyingPeriodController extends AbstractController
'element_class' => AccompanyingPeriod::class,
'action' => 'list',
]);
$this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event);
$this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);
$accompanyingPeriods = $this->accompanyingPeriodACLAwareRepository
->findByPerson($person, AccompanyingPeriodVoter::SEE, ["openingDate" => "DESC", "id" => "DESC"]);
->findByPerson($person, AccompanyingPeriodVoter::SEE, ['openingDate' => 'DESC', 'id' => 'DESC']);
//usort($accompanyingPeriodsRaw, static fn ($a, $b) => $b->getOpeningDate() <=> $a->getOpeningDate());
// usort($accompanyingPeriodsRaw, static fn ($a, $b) => $b->getOpeningDate() <=> $a->getOpeningDate());
// filter visible or not visible
//$accompanyingPeriods = array_filter($accompanyingPeriodsRaw, fn (AccompanyingPeriod $ap) => $this->isGranted(AccompanyingPeriodVoter::SEE, $ap));
// $accompanyingPeriods = array_filter($accompanyingPeriodsRaw, fn (AccompanyingPeriod $ap) => $this->isGranted(AccompanyingPeriodVoter::SEE, $ap));
return $this->render('@ChillPerson/AccompanyingPeriod/list.html.twig', [
'accompanying_periods' => $accompanyingPeriods,
@@ -233,6 +218,9 @@ class AccompanyingPeriodController extends AbstractController
]);
}
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/accompanying-period/open", name="chill_person_accompanying_period_open")
*/
public function openAction(int $person_id, Request $request): Response
{
$person = $this->_getPerson($person_id);
@@ -243,23 +231,21 @@ class AccompanyingPeriodController extends AbstractController
'You are not allowed to update this person'
);
//in case the person is already open
// in case the person is already open
if ($person->isOpen()) {
$this->get('session')->getFlashBag()
->add('error', $this->get('translator')
->add('error', $this->translator
->trans(
'Error! Period %name% is not closed ; it can be open',
['%name%' => $person->__toString()]
));
return $this->redirect(
$this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
])
);
return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
]);
}
$accompanyingPeriod = new AccompanyingPeriod(new DateTime());
$accompanyingPeriod = new AccompanyingPeriod(new \DateTime());
$form = $this->createForm(
AccompanyingPeriodType::class,
@@ -270,7 +256,7 @@ class AccompanyingPeriodController extends AbstractController
]
);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -278,9 +264,9 @@ class AccompanyingPeriodController extends AbstractController
$errors = $this->_validatePerson($person);
if (count($errors) <= 0) {
if (\count($errors) <= 0) {
$this->get('session')->getFlashBag()
->add('success', $this->get('translator')
->add('success', $this->translator
->trans(
'An accompanying period has been opened.',
['%name%' => $person->__toString()]
@@ -288,14 +274,12 @@ class AccompanyingPeriodController extends AbstractController
$this->getDoctrine()->getManager()->flush();
return $this->redirect(
$this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
])
);
return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
]);
}
$this->get('session')->getFlashBag()
->add('error', $this->get('translator')
->add('error', $this->translator
->trans('Period not opened'));
foreach ($errors as $error) {
@@ -306,28 +290,31 @@ class AccompanyingPeriodController extends AbstractController
$this->get('session')->getFlashBag()
->add(
'error',
$this->get('translator')
$this->translator
->trans('Period not opened : form is invalid')
);
}
}
return $this->render('ChillPersonBundle:AccompanyingPeriod:form.html.twig', [
return $this->render('@ChillPerson/AccompanyingPeriod/form.html.twig', [
'form' => $form->createView(),
'person' => $person,
'accompanying_period' => $accompanyingPeriod,
]);
}
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/accompanying-period/{period_id}/re-open", name="chill_person_accompanying_period_re_open")
*/
public function reOpenAction(int $person_id, int $period_id, Request $request): Response
{
/** @var Person $person */
$person = $this->_getPerson($person_id);
/** @var AccompanyingPeriod $period */
$period = array_filter(
$period = \array_filter(
$person->getAccompanyingPeriods(),
static fn (AccompanyingPeriod $p) => $p->getId() === ($period_id)
static fn (AccompanyingPeriod $p) => $p->getId() === $period_id
)[0] ?? null;
if (null === $period) {
@@ -343,7 +330,7 @@ class AccompanyingPeriodController extends AbstractController
$this->getDoctrine()->getManager()->flush();
$this->addFlash('success', $this->get('translator')->trans(
$this->addFlash('success', $this->translator->trans(
'The period has been re-opened'
));
@@ -353,7 +340,7 @@ class AccompanyingPeriodController extends AbstractController
}
if (false === $confirm && $period->canBeReOpened($person)) {
return $this->render('ChillPersonBundle:AccompanyingPeriod:re_open.html.twig', [
return $this->render('@ChillPerson/AccompanyingPeriod/re_open.html.twig', [
'period' => $period,
'person' => $person,
]);
@@ -366,6 +353,8 @@ class AccompanyingPeriodController extends AbstractController
/**
* @throws Exception
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/accompanying-period/{period_id}/update", name="chill_person_accompanying_period_update")
*/
public function updateAction(int $person_id, int $period_id, Request $request): Response
{
@@ -375,7 +364,7 @@ class AccompanyingPeriodController extends AbstractController
$accompanyingPeriod = $em->getRepository(AccompanyingPeriod::class)->find($period_id);
if (null === $accompanyingPeriod) {
throw $this->createNotFoundException('Period with id ' . $period_id . ' is not found');
throw $this->createNotFoundException('Period with id '.$period_id.' is not found');
}
/** @var Person $person */
@@ -383,7 +372,7 @@ class AccompanyingPeriodController extends AbstractController
// CHECK
if (!$accompanyingPeriod->containsPerson($person)) {
throw new Exception('Accompanying period ' . $period_id . ' does not contain person ' . $person_id);
throw new Exception('Accompanying period '.$period_id.' does not contain person '.$person_id);
}
$this->denyAccessUnlessGranted(
@@ -401,30 +390,28 @@ class AccompanyingPeriodController extends AbstractController
]
);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
$errors = $this->_validatePerson($person);
$flashBag = $this->get('session')->getFlashBag();
if (
$form->isValid(['Default', 'closed'])
&& count($errors) === 0
&& 0 === \count($errors)
) {
$em->flush();
$flashBag->add(
'success',
$this->get('translator')->trans('An accompanying period has been updated.')
$this->translator->trans('An accompanying period has been updated.')
);
return $this->redirect(
$this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
])
);
return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person->getId(),
]);
}
$flashBag->add('error', $this->get('translator')
$flashBag->add('error', $this->translator
->trans('Error when updating the period'));
foreach ($errors as $error) {
@@ -432,7 +419,7 @@ class AccompanyingPeriodController extends AbstractController
}
}
return $this->render('ChillPersonBundle:AccompanyingPeriod:form.html.twig', [
return $this->render('@ChillPerson/AccompanyingPeriod/form.html.twig', [
'form' => $form->createView(),
'person' => $person,
'accompanying_period' => $accompanyingPeriod,
@@ -445,7 +432,7 @@ class AccompanyingPeriodController extends AbstractController
private function _getPerson(int $id): Person
{
$person = $this->getDoctrine()->getManager()
->getRepository(\Chill\PersonBundle\Entity\Person::class)->find($id);
->getRepository(Person::class)->find($id);
if (null === $person) {
throw $this->createNotFoundException('Person not found');

View File

@@ -28,30 +28,11 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
class AccompanyingPeriodRegulationListController
{
private AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository;
private EngineInterface $engine;
private FormFactoryInterface $formFactory;
private PaginatorFactory $paginatorFactory;
private Security $security;
private TranslatableStringHelperInterface $translatableStringHelper;
public function __construct(AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository, EngineInterface $engine, FormFactoryInterface $formFactory, PaginatorFactory $paginatorFactory, Security $security, TranslatableStringHelperInterface $translatableStringHelper)
public function __construct(private readonly AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository, private readonly \Twig\Environment $engine, private readonly FormFactoryInterface $formFactory, private readonly PaginatorFactory $paginatorFactory, private readonly Security $security, private readonly TranslatableStringHelperInterface $translatableStringHelper)
{
$this->accompanyingPeriodACLAwareRepository = $accompanyingPeriodACLAwareRepository;
$this->engine = $engine;
$this->formFactory = $formFactory;
$this->paginatorFactory = $paginatorFactory;
$this->security = $security;
$this->translatableStringHelper = $translatableStringHelper;
}
/**

View File

@@ -27,33 +27,10 @@ use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use function count;
use function in_array;
class AccompanyingPeriodWorkEvaluationApiController
{
private AccompanyingPeriodWorkEvaluationRepository $accompanyingPeriodWorkEvaluationRepository;
private DocGeneratorTemplateRepository $docGeneratorTemplateRepository;
private PaginatorFactory $paginatorFactory;
private Security $security;
private SerializerInterface $serializer;
public function __construct(
AccompanyingPeriodWorkEvaluationRepository $accompanyingPeriodWorkEvaluationRepository,
DocGeneratorTemplateRepository $docGeneratorTemplateRepository,
SerializerInterface $serializer,
PaginatorFactory $paginatorFactory,
Security $security
) {
$this->accompanyingPeriodWorkEvaluationRepository = $accompanyingPeriodWorkEvaluationRepository;
$this->docGeneratorTemplateRepository = $docGeneratorTemplateRepository;
$this->serializer = $serializer;
$this->paginatorFactory = $paginatorFactory;
$this->security = $security;
public function __construct(private readonly AccompanyingPeriodWorkEvaluationRepository $accompanyingPeriodWorkEvaluationRepository, private readonly DocGeneratorTemplateRepository $docGeneratorTemplateRepository, private readonly SerializerInterface $serializer, private readonly PaginatorFactory $paginatorFactory, private readonly Security $security)
{
}
/**
@@ -73,12 +50,12 @@ class AccompanyingPeriodWorkEvaluationApiController
static function (DocGeneratorTemplate $t) use ($evaluation) {
$ids = $t->getOptions()['evaluations'] ?? [];
return in_array($evaluation->getId(), $ids, true);
return \in_array($evaluation->getId(), $ids, true);
}
);
$paginator = $this->paginatorFactory->create(count($evaluations));
$paginator->setItemsPerPage(count($evaluations));
$paginator = $this->paginatorFactory->create(\count($evaluations));
$paginator->setItemsPerPage(\count($evaluations));
return new JsonResponse($this->serializer->serialize(
new Collection(array_values($evaluations), $paginator),

View File

@@ -24,7 +24,7 @@ class AdminController extends AbstractController
*/
public function indexAccompanyingCourseAdminAction()
{
return $this->render('ChillPersonBundle:Admin:indexAccompanyingCourse.html.twig');
return $this->render('@ChillPerson/Admin/indexAccompanyingCourse.html.twig');
}
/**
@@ -32,7 +32,7 @@ class AdminController extends AbstractController
*/
public function indexHouseholdAdminAction()
{
return $this->render('ChillPersonBundle:Admin:indexHousehold.html.twig');
return $this->render('@ChillPerson/Admin/indexHousehold.html.twig');
}
/**
@@ -40,7 +40,7 @@ class AdminController extends AbstractController
*/
public function indexPersonAdminAction()
{
return $this->render('ChillPersonBundle:Admin:indexPerson.html.twig');
return $this->render('@ChillPerson/Admin/indexPerson.html.twig');
}
/**
@@ -48,11 +48,13 @@ class AdminController extends AbstractController
*/
public function indexSocialWorkAdminAction()
{
return $this->render('ChillPersonBundle:Admin:indexSocialWork.html.twig');
return $this->render('@ChillPerson/Admin/indexSocialWork.html.twig');
}
/**
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/person_redirect_to_main", name="chill_person_admin_redirect_to_admin_index", options={null})
*/
public function redirectToAdminIndexAction()
{

View File

@@ -52,7 +52,7 @@ class ClosingMotiveController extends CRUDController
*/
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)
{
/** @var \Doctrine\ORM\QueryBuilder $query */
/* @var \Doctrine\ORM\QueryBuilder $query */
return $query->orderBy('e.ordering', 'ASC');
}
}

View File

@@ -22,33 +22,17 @@ use Chill\PersonBundle\Event\Person\PersonAddressMoveEvent;
use Chill\PersonBundle\Repository\Household\HouseholdACLAwareRepositoryInterface;
use Chill\PersonBundle\Repository\Household\HouseholdRepository;
use Chill\PersonBundle\Security\Authorization\HouseholdVoter;
use DateTimeImmutable;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use function array_filter;
use function array_values;
class HouseholdApiController extends ApiController
{
private EventDispatcherInterface $eventDispatcher;
private HouseholdACLAwareRepositoryInterface $householdACLAwareRepository;
private HouseholdRepository $householdRepository;
public function __construct(
EventDispatcherInterface $eventDispatcher,
HouseholdRepository $householdRepository,
HouseholdACLAwareRepositoryInterface $householdACLAwareRepository
) {
$this->eventDispatcher = $eventDispatcher;
$this->householdRepository = $householdRepository;
$this->householdACLAwareRepository = $householdACLAwareRepository;
public function __construct(private readonly EventDispatcherInterface $eventDispatcher, private readonly HouseholdRepository $householdRepository, private readonly HouseholdACLAwareRepositoryInterface $householdACLAwareRepository)
{
}
/**
@@ -93,9 +77,9 @@ class HouseholdApiController extends ApiController
$household->addAddress($address);
foreach ($household->getMembersOnRange(
DateTimeImmutable::createFromMutable($address->getValidFrom()),
\DateTimeImmutable::createFromMutable($address->getValidFrom()),
null === $address->getValidTo() ? null :
DateTimeImmutable::createFromMutable($address->getValidTo())
\DateTimeImmutable::createFromMutable($address->getValidTo())
) as $member) {
/** @var HouseholdMember $member */
$event = new PersonAddressMoveEvent($member->getPerson());
@@ -128,6 +112,7 @@ class HouseholdApiController extends ApiController
* "_format": "json"
* }
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function suggestAddressByHousehold(Household $household, string $_format)
@@ -160,11 +145,11 @@ class HouseholdApiController extends ApiController
$actual = $household->getCurrentAddress();
if (null !== $actual) {
$addresses = array_filter($addresses, static fn ($a) => $a !== $actual);
$addresses = \array_filter($addresses, static fn ($a) => $a !== $actual);
}
return $this->json(
array_values($addresses),
\array_values($addresses),
Response::HTTP_OK,
[],
['groups' => ['read']]
@@ -200,7 +185,7 @@ class HouseholdApiController extends ApiController
}
if (null !== $currentHouseholdPerson) {
$count = $count - 1;
--$count;
$paginator = $this->getPaginatorFactory()->create($count);
}
}

View File

@@ -18,7 +18,6 @@ use Chill\PersonBundle\Form\HouseholdCompositionType;
use Chill\PersonBundle\Repository\Household\HouseholdCompositionRepository;
use Chill\PersonBundle\Repository\Household\HouseholdRepository;
use Chill\PersonBundle\Security\Authorization\HouseholdVoter;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@@ -31,58 +30,27 @@ use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class HouseholdCompositionController extends AbstractController
{
private EngineInterface $engine;
private EntityManagerInterface $entityManager;
private FormFactoryInterface $formFactory;
private HouseholdCompositionRepository $householdCompositionRepository;
private HouseholdRepository $householdRepository;
private PaginatorFactory $paginatorFactory;
private Security $security;
private TranslatorInterface $translator;
private UrlGeneratorInterface $urlGenerator;
public function __construct(
Security $security,
HouseholdCompositionRepository $householdCompositionRepository,
HouseholdRepository $householdRepository,
PaginatorFactory $paginatorFactory,
FormFactoryInterface $formFactory,
EntityManagerInterface $entityManager,
TranslatorInterface $translator,
EngineInterface $engine,
UrlGeneratorInterface $urlGenerator
private readonly Security $security,
private readonly HouseholdCompositionRepository $householdCompositionRepository,
private readonly HouseholdRepository $householdRepository,
private readonly PaginatorFactory $paginatorFactory,
private readonly FormFactoryInterface $formFactory,
private readonly EntityManagerInterface $entityManager,
private readonly TranslatorInterface $translator,
private readonly \Twig\Environment $engine,
private readonly UrlGeneratorInterface $urlGenerator
) {
$this->security = $security;
$this->householdCompositionRepository = $householdCompositionRepository;
$this->paginatorFactory = $paginatorFactory;
$this->formFactory = $formFactory;
$this->entityManager = $entityManager;
$this->translator = $translator;
$this->engine = $engine;
$this->urlGenerator = $urlGenerator;
$this->householdRepository = $householdRepository;
}
/**
* @Route("/{_locale}/person/household/{household_id}/composition/{composition_id}/delete", name="chill_person_household_composition_delete")
*
* @param mixed $household_id
* @param mixed $composition_id
*/
public function deleteAction(Request $request, $household_id, $composition_id): Response
public function deleteAction(Request $request, mixed $household_id, mixed $composition_id): Response
{
$composition = $this->householdCompositionRepository->find($composition_id);
$household = $this->householdRepository->find($household_id);
@@ -102,7 +70,7 @@ class HouseholdCompositionController extends AbstractController
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
if ($request->getMethod() === Request::METHOD_DELETE) {
if (Request::METHOD_DELETE === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -119,7 +87,7 @@ class HouseholdCompositionController extends AbstractController
}
return $this->render(
'ChillPersonBundle:HouseholdComposition:delete.html.twig',
'@ChillPerson/HouseholdComposition/delete.html.twig',
[
'household' => $household,
'composition' => $composition,
@@ -166,13 +134,13 @@ class HouseholdCompositionController extends AbstractController
if ($isEdit) {
$householdCompositions = $household->getCompositions()->filter(static fn (HouseholdComposition $composition) => $composition->getId() === $request->query->getInt('edit'));
if ($householdCompositions->count() !== 1) {
if (1 !== $householdCompositions->count()) {
throw new BadRequestHttpException('could not find the composition with this id associated to the household');
}
$householdComposition = $householdCompositions->first();
} else {
$householdComposition = (new HouseholdComposition())
->setStartDate(new DateTimeImmutable());
->setStartDate(new \DateTimeImmutable());
}
$form = $this->formFactory->create(HouseholdCompositionType::class, $householdComposition);

View File

@@ -14,7 +14,6 @@ namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use UnexpectedValueException;
class HouseholdCompositionTypeApiController extends ApiController
{
@@ -23,14 +22,9 @@ class HouseholdCompositionTypeApiController extends ApiController
*/
protected function customizeQuery(string $action, Request $request, $query): void
{
switch ($action) {
case '_index':
$query->andWhere($query->expr()->eq('e.active', "'TRUE'"));
break;
default:
throw new UnexpectedValueException('unexepcted action: ' . $action);
}
match ($action) {
'_index' => $query->andWhere($query->expr()->eq('e.active', "'TRUE'")),
default => throw new \UnexpectedValueException('unexepcted action: '.$action),
};
}
}

View File

@@ -29,32 +29,13 @@ use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
use function count;
/**
* @Route("/{_locale}/person/household")
*/
class HouseholdController extends AbstractController
{
private PositionRepository $positionRepository;
private Security $security;
private SerializerInterface $serializer;
private TranslatorInterface $translator;
public function __construct(
TranslatorInterface $translator,
PositionRepository $positionRepository,
SerializerInterface $serializer,
Security $security
) {
$this->translator = $translator;
$this->positionRepository = $positionRepository;
$this->serializer = $serializer;
$this->security = $security;
public function __construct(private readonly TranslatorInterface $translator, private readonly PositionRepository $positionRepository, private readonly SerializerInterface $serializer, private readonly Security $security)
{
}
/**
@@ -63,6 +44,7 @@ class HouseholdController extends AbstractController
* name="chill_person_household_accompanying_period",
* methods={"GET", "HEAD"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function accompanyingPeriod(Request $request, Household $household)
@@ -95,7 +77,7 @@ class HouseholdController extends AbstractController
}
$id = $accompanyingPeriod->getId();
if (!array_key_exists($id, $accompanyingPeriodsOld) && !array_key_exists($id, $accompanyingPeriods)) {
if (!\array_key_exists($id, $accompanyingPeriodsOld) && !\array_key_exists($id, $accompanyingPeriods)) {
$accompanyingPeriodsOld[$id] = $accompanyingPeriod;
}
}
@@ -117,6 +99,7 @@ class HouseholdController extends AbstractController
* name="chill_person_household_address_edit",
* methods={"GET", "HEAD", "POST"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function addressEdit(Request $request, Household $household)
@@ -143,17 +126,18 @@ class HouseholdController extends AbstractController
* name="chill_person_household_addresses",
* methods={"GET", "HEAD"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function addresses(Request $request, Household $household)
{
// TODO ACL
//TODO put these lines into a validator constraint on household->getAddress
// TODO put these lines into a validator constraint on household->getAddress
$addresses = $household->getAddresses();
$cond = true;
for ($i = 0; count($addresses) - 1 > $i; ++$i) {
for ($i = 0; \count($addresses) - 1 > $i; ++$i) {
if ($addresses[$i]->getValidFrom() !== $addresses[$i + 1]->getValidTo()) {
$cond = false;
}
@@ -173,6 +157,7 @@ class HouseholdController extends AbstractController
* name="chill_person_household_address_move",
* methods={"GET", "HEAD", "POST"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function addressMove(Request $request, Household $household)
@@ -193,6 +178,7 @@ class HouseholdController extends AbstractController
* name="chill_person_household_address_valid_from_edit",
* methods={"GET", "HEAD", "POST"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function addressValidFromEdit(Request $request, Household $household)
@@ -249,6 +235,7 @@ class HouseholdController extends AbstractController
* name="chill_person_household_members_metadata_edit",
* methods={"GET", "POST"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function editHouseholdMetadata(Request $request, Household $household)
@@ -280,6 +267,7 @@ class HouseholdController extends AbstractController
* name="chill_person_household_relationship",
* methods={"GET", "HEAD"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function showRelationship(Request $request, Household $household)
@@ -305,6 +293,7 @@ class HouseholdController extends AbstractController
* name="chill_person_household_summary",
* methods={"GET", "HEAD"}
* )
*
* @ParamConverter("household", options={"id": "household_id"})
*/
public function summary(Request $request, Household $household)

View File

@@ -28,24 +28,10 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\Exception;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
class HouseholdMemberController extends ApiController
{
private UrlGeneratorInterface $generator;
private AccompanyingPeriodRepository $periodRepository;
private TranslatorInterface $translator;
public function __construct(
UrlGeneratorInterface $generator,
TranslatorInterface $translator,
AccompanyingPeriodRepository $periodRepository
) {
$this->generator = $generator;
$this->translator = $translator;
$this->periodRepository = $periodRepository;
public function __construct(private readonly UrlGeneratorInterface $generator, private readonly TranslatorInterface $translator, private readonly AccompanyingPeriodRepository $periodRepository)
{
}
/**
@@ -104,9 +90,8 @@ class HouseholdMemberController extends ApiController
if ($request->query->has('persons')) {
$ids = $request->query->get('persons', []);
if (0 === count($ids)) {
throw new BadRequestHttpException('parameters persons in query ' .
'is not an array or empty');
if (0 === \count($ids)) {
throw new BadRequestHttpException('parameters persons in query is not an array or empty');
}
$persons = $em->getRepository(Person::class)
@@ -175,10 +160,8 @@ class HouseholdMemberController extends ApiController
* "/api/1.0/person/household/members/move.{_format}",
* name="chill_api_person_household_members_move"
* )
*
* @param mixed $_format
*/
public function move(Request $request, $_format): Response
public function move(Request $request, mixed $_format): Response
{
try {
/** @var MembersEditor $editor */
@@ -197,7 +180,7 @@ class HouseholdMemberController extends ApiController
//
$errors = $editor->validate();
if (count($errors) > 0) {
if (\count($errors) > 0) {
return $this->json($errors, 422);
}

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use DateTime;
use Symfony\Component\HttpFoundation\Request;
class OpeningApiController extends ApiController
@@ -21,6 +20,6 @@ class OpeningApiController extends ApiController
{
$qb->where($qb->expr()->gt('e.noActiveAfter', ':now'))
->orWhere($qb->expr()->isNull('e.noActiveAfter'));
$qb->setParameter('now', new DateTime('now'));
$qb->setParameter('now', new \DateTime('now'));
}
}

View File

@@ -18,8 +18,7 @@ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use function count;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Class PersonAddressController
@@ -27,28 +26,24 @@ use function count;
*/
class PersonAddressController extends AbstractController
{
/**
* @var ValidatorInterface
*/
protected $validator;
/**
* PersonAddressController constructor.
*/
public function __construct(ValidatorInterface $validator)
public function __construct(private readonly ValidatorInterface $validator, private readonly TranslatorInterface $translator)
{
$this->validator = $validator;
}
public function createAction($person_id, Request $request)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/address/create", name="chill_person_address_create", methods={"POST"})
*/
public function createAction(mixed $person_id, Request $request)
{
$person = $this->getDoctrine()->getManager()
->getRepository(\Chill\PersonBundle\Entity\Person::class)
->getRepository(Person::class)
->find($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found ');
throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
}
$this->denyAccessUnlessGranted(
@@ -67,7 +62,7 @@ class PersonAddressController extends AbstractController
if ($form->isSubmitted() && $form->isValid()) {
$validatePersonErrors = $this->validatePerson($person);
if (count($validatePersonErrors) !== 0) {
if (0 !== \count($validatePersonErrors)) {
foreach ($validatePersonErrors as $error) {
$this->addFlash('error', $error->getMessage());
}
@@ -77,33 +72,35 @@ class PersonAddressController extends AbstractController
$this->addFlash(
'success',
$this->get('translator')->trans('The new address was created successfully')
$this->translator->trans('The new address was created successfully')
);
return $this->redirectToRoute('chill_person_address_list', [
'person_id' => $person->getId(),
]);
} else {
$this->addFlash('error', $this->get('translator')
$this->addFlash('error', $this->translator
->trans('Error! Address not created!'));
}
}
return $this->render('ChillPersonBundle:Address:new.html.twig', [
return $this->render('@ChillPerson/Address/new.html.twig', [
'person' => $person,
'form' => $form->createView(),
]);
}
public function editAction($person_id, $address_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/address/{address_id}/edit", name="chill_person_address_edit")
*/
public function editAction(mixed $person_id, mixed $address_id)
{
$person = $this->getDoctrine()->getManager()
->getRepository(\Chill\PersonBundle\Entity\Person::class)
->getRepository(Person::class)
->find($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found ');
throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
}
$this->denyAccessUnlessGranted(
@@ -116,22 +113,24 @@ class PersonAddressController extends AbstractController
$form = $this->createEditForm($person, $address);
return $this->render('ChillPersonBundle:Address:edit.html.twig', [
return $this->render('@ChillPerson/Address/edit.html.twig', [
'person' => $person,
'address' => $address,
'form' => $form->createView(),
]);
}
public function listAction($person_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/address/list", name="chill_person_address_list")
*/
public function listAction(mixed $person_id)
{
$person = $this->getDoctrine()->getManager()
->getRepository(\Chill\PersonBundle\Entity\Person::class)
->getRepository(Person::class)
->find($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found ');
throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
}
$this->denyAccessUnlessGranted(
@@ -140,20 +139,22 @@ class PersonAddressController extends AbstractController
'You are not allowed to edit this person.'
);
return $this->render('ChillPersonBundle:Address:list.html.twig', [
return $this->render('@ChillPerson/Address/list.html.twig', [
'person' => $person,
]);
}
public function newAction($person_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/address/new", name="chill_person_address_new")
*/
public function newAction(mixed $person_id)
{
$person = $this->getDoctrine()->getManager()
->getRepository(\Chill\PersonBundle\Entity\Person::class)
->getRepository(Person::class)
->find($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found ');
throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
}
$this->denyAccessUnlessGranted(
@@ -166,21 +167,23 @@ class PersonAddressController extends AbstractController
$form = $this->createCreateForm($person, $address);
return $this->render('ChillPersonBundle:Address:new.html.twig', [
return $this->render('@ChillPerson/Address/new.html.twig', [
'person' => $person,
'form' => $form->createView(),
]);
}
public function updateAction($person_id, $address_id, Request $request)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/address/{address_id}/update", name="chill_person_address_update")
*/
public function updateAction(mixed $person_id, mixed $address_id, Request $request)
{
$person = $this->getDoctrine()->getManager()
->getRepository(\Chill\PersonBundle\Entity\Person::class)
->getRepository(Person::class)
->find($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found ');
throw $this->createNotFoundException("Person with id {$person_id} not".' found ');
}
$this->denyAccessUnlessGranted(
@@ -197,7 +200,7 @@ class PersonAddressController extends AbstractController
if ($form->isSubmitted() && $form->isValid()) {
$validatePersonErrors = $this->validatePerson($person);
if (count($validatePersonErrors) !== 0) {
if (0 !== \count($validatePersonErrors)) {
foreach ($validatePersonErrors as $error) {
$this->addFlash('error', $error->getMessage());
}
@@ -205,7 +208,7 @@ class PersonAddressController extends AbstractController
$this->getDoctrine()->getManager()
->flush();
$this->addFlash('success', $this->get('translator')->trans(
$this->addFlash('success', $this->translator->trans(
'The address has been successfully updated'
));
@@ -213,12 +216,12 @@ class PersonAddressController extends AbstractController
'person_id' => $person->getId(),
]);
} else {
$this->addFlash('error', $this->get('translator')
$this->addFlash('error', $this->translator
->trans('Error when updating the period'));
}
}
return $this->render('ChillPersonBundle:Address:edit.html.twig', [
return $this->render('@ChillPerson/Address/edit.html.twig', [
'person' => $person,
'address' => $address,
'form' => $form->createView(),
@@ -269,9 +272,9 @@ class PersonAddressController extends AbstractController
/**
* @param int $address_id
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the address id does not exists or is not associated with given person
*
* @return Address
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the address id does not exists or is not associated with given person
*/
protected function findAddressById(Person $person, $address_id)
{
@@ -287,8 +290,6 @@ class PersonAddressController extends AbstractController
}
/**
* @param Chill\PersonBundle\Entity\Person $person
*
* @return \Symfony\Component\Validator\ConstraintViolationListInterface
*/
private function validatePerson(Person $person)

View File

@@ -23,23 +23,16 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use function in_array;
class PersonApiController extends ApiController
{
private AuthorizedCenterOnPersonCreationInterface $authorizedCenterOnPersonCreation;
private ConfigPersonAltNamesHelper $configPersonAltNameHelper;
private bool $showCenters;
private readonly bool $showCenters;
public function __construct(
AuthorizedCenterOnPersonCreationInterface $authorizedCenterOnPersonCreation,
ConfigPersonAltNamesHelper $configPersonAltNameHelper,
private readonly AuthorizedCenterOnPersonCreationInterface $authorizedCenterOnPersonCreation,
private readonly ConfigPersonAltNamesHelper $configPersonAltNameHelper,
ParameterBagInterface $parameterBag
) {
$this->authorizedCenterOnPersonCreation = $authorizedCenterOnPersonCreation;
$this->configPersonAltNameHelper = $configPersonAltNameHelper;
$this->showCenters = $parameterBag->get('chill_main')['acl']['form_show_centers'];
}
@@ -56,7 +49,7 @@ class PersonApiController extends ApiController
['showCenters' => $this->showCenters, 'centers' => $centers],
Response::HTTP_OK,
[],
['gropus' => ['read']]
['groups' => ['read']]
);
}
@@ -96,6 +89,7 @@ class PersonApiController extends ApiController
* "_format": "json"
* }
* )
*
* @ParamConverter("person", options={"id": "person_id"})
*/
public function suggestAddress(Person $person, Request $request, string $_format): Response
@@ -121,7 +115,7 @@ class PersonApiController extends ApiController
static function (Address $address) use (&$seenAddressIds): bool {
$id = $address->getId();
if (in_array($id, $seenAddressIds, true)) {
if (\in_array($id, $seenAddressIds, true)) {
return false;
}

View File

@@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface;
use Chill\PersonBundle\Config\ConfigPersonAltNamesHelper;
use Chill\PersonBundle\Entity\Household\Household;
@@ -23,9 +22,7 @@ use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\PersonBundle\Repository\PersonRepository;
use Chill\PersonBundle\Search\SimilarPersonMatcher;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
@@ -35,83 +32,28 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
use function hash;
use function implode;
use function in_array;
use function is_array;
final class PersonController extends AbstractController
{
private AuthorizationHelperInterface $authorizationHelper;
/**
* @var ConfigPersonAltNamesHelper
*/
protected $configPersonAltNameHelper;
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @var PersonRepository;
*/
protected $personRepository;
/**
* @var SimilarPersonMatcher
*/
protected $similarPersonMatcher;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
/**
* @var ValidatorInterface
*/
private $validator;
public function __construct(
AuthorizationHelperInterface $authorizationHelper,
SimilarPersonMatcher $similarPersonMatcher,
TranslatorInterface $translator,
EventDispatcherInterface $eventDispatcher,
PersonRepository $personRepository,
ConfigPersonAltNamesHelper $configPersonAltNameHelper,
LoggerInterface $logger,
ValidatorInterface $validator,
EntityManagerInterface $em,
private readonly AuthorizationHelperInterface $authorizationHelper,
private readonly SimilarPersonMatcher $similarPersonMatcher,
private readonly TranslatorInterface $translator,
private readonly EventDispatcherInterface $eventDispatcher,
private readonly PersonRepository $personRepository,
private readonly ConfigPersonAltNamesHelper $configPersonAltNameHelper,
private readonly ValidatorInterface $validator,
private readonly EntityManagerInterface $em,
) {
$this->authorizationHelper = $authorizationHelper;
$this->similarPersonMatcher = $similarPersonMatcher;
$this->translator = $translator;
$this->eventDispatcher = $eventDispatcher;
$this->configPersonAltNameHelper = $configPersonAltNameHelper;
$this->personRepository = $personRepository;
$this->logger = $logger;
$this->validator = $validator;
$this->em = $em;
}
public function editAction($person_id, Request $request)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/general/edit", name="chill_person_general_edit")
*/
public function editAction(int $person_id, Request $request)
{
$person = $this->_getPerson($person_id);
@@ -145,7 +87,7 @@ final class PersonController extends AbstractController
$this->get('session')->getFlashBag()
->add(
'success',
$this->get('translator')
$this->translator
->trans('The person data has been updated')
);
@@ -155,7 +97,7 @@ final class PersonController extends AbstractController
}
return $this->render(
'ChillPersonBundle:Person:edit.html.twig',
'@ChillPerson/Person/edit.html.twig',
['person' => $person, 'form' => $form->createView()]
);
}
@@ -165,7 +107,7 @@ final class PersonController extends AbstractController
$cFGroup = null;
$cFDefaultGroup = $this->em->getRepository(\Chill\CustomFieldsBundle\Entity\CustomFieldsDefaultGroup::class)
->findOneByEntity(\Chill\PersonBundle\Entity\Person::class);
->findOneByEntity(Person::class);
if ($cFDefaultGroup) {
$cFGroup = $cFDefaultGroup->getCustomFieldsGroup();
@@ -180,6 +122,7 @@ final class PersonController extends AbstractController
* name="chill_person_household_person_history",
* methods={"GET", "POST"}
* )
*
* @ParamConverter("person", options={"id": "person_id"})
*/
public function householdHistoryByPerson(Request $request, Person $person): Response
@@ -191,7 +134,7 @@ final class PersonController extends AbstractController
);
$event = new PrivacyEvent($person);
$this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event);
$this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);
return $this->render(
'@ChillPerson/Person/household_history.html.twig',
@@ -209,14 +152,16 @@ final class PersonController extends AbstractController
*
* The next post compare the data with previous one and, if yes, show a
* review page if there are "alternate persons".
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/new", name="chill_person_new")
*/
public function newAction(Request $request): Response
{
$person = new Person();
$authorizedCenters =$this->authorizationHelper->getReachableCenters($this->getUser(), PersonVoter::CREATE);
$authorizedCenters = $this->authorizationHelper->getReachableCenters($this->getUser(), PersonVoter::CREATE);
if (1 === count($authorizedCenters)) {
if (1 === \count($authorizedCenters)) {
$person->setCenter($authorizedCenters[0]);
}
@@ -231,10 +176,10 @@ final class PersonController extends AbstractController
$form->handleRequest($request);
if ($request->getMethod() === Request::METHOD_GET) {
if (Request::METHOD_GET === $request->getMethod()) {
$this->lastPostDataReset();
} elseif (
$request->getMethod() === Request::METHOD_POST
Request::METHOD_POST === $request->getMethod()
&& $form->isValid()
) {
$alternatePersons = $this->similarPersonMatcher
@@ -242,7 +187,7 @@ final class PersonController extends AbstractController
if (
false === $this->isLastPostDataChanges($form, $request, true)
|| count($alternatePersons) === 0
|| 0 === \count($alternatePersons)
) {
$this->em->persist($person);
@@ -257,7 +202,7 @@ final class PersonController extends AbstractController
$member = new HouseholdMember();
$member->setPerson($person);
$member->setStartDate(new DateTimeImmutable());
$member->setStartDate(new \DateTimeImmutable());
$household->addMember($member);
$household->setForceAddress($address);
@@ -291,7 +236,7 @@ final class PersonController extends AbstractController
['person_id' => $person->getId()]
);
}
} elseif ($request->getMethod() === Request::METHOD_POST && !$form->isValid()) {
} elseif (Request::METHOD_POST === $request->getMethod() && !$form->isValid()) {
$this->addFlash('error', $this->translator->trans('This form contains errors'));
}
@@ -304,13 +249,15 @@ final class PersonController extends AbstractController
);
}
public function viewAction($person_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/general", name="chill_person_view")
*/
public function viewAction(int $person_id)
{
$person = $this->_getPerson($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person_id} not".' found on this server');
}
$this->denyAccessUnlessGranted(
@@ -320,10 +267,10 @@ final class PersonController extends AbstractController
);
$event = new PrivacyEvent($person);
$this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event);
$this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);
return $this->render(
'ChillPersonBundle:Person:view.html.twig',
'@ChillPerson/Person/view.html.twig',
[
'person' => $person,
'cFGroup' => $this->getCFGroup(),
@@ -335,11 +282,9 @@ final class PersonController extends AbstractController
/**
* easy getting a person by his id.
*
* @param mixed $id
*
* @return \Chill\PersonBundle\Entity\Person
* @return Person
*/
private function _getPerson($id)
private function _getPerson(int $id)
{
return $this->personRepository->find($id);
}
@@ -352,14 +297,14 @@ final class PersonController extends AbstractController
$errors = $this->validator
->validate($person, null, ['creation']);
//validate accompanying periods
// validate accompanying periods
$periods = $person->getAccompanyingPeriods();
foreach ($periods as $period) {
$period_errors = $this->validator
->validate($period);
//group errors :
// group errors :
foreach ($period_errors as $error) {
$errors->add($error);
}
@@ -399,15 +344,15 @@ final class PersonController extends AbstractController
$ignoredFields = ['form_status', '_token'];
foreach ($request->request->all()[$form->getName()] as $field => $value) {
if (in_array($field, $ignoredFields, true)) {
if (\in_array($field, $ignoredFields, true)) {
continue;
}
$fields[$field] = is_array($value) ?
implode(',', $value) : $value;
$fields[$field] = \is_array($value) ?
\implode(',', $value) : $value;
}
ksort($fields);
return hash('sha512', implode('&', $fields));
return \hash('sha512', \implode('&', $fields));
}
private function lastPostDataReset(): void

View File

@@ -25,55 +25,21 @@ use Chill\PersonBundle\Repository\PersonRepository;
use Chill\PersonBundle\Search\SimilarPersonMatcher;
use Chill\TaskBundle\Entity\SingleTask;
use http\Exception\InvalidArgumentException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
class PersonDuplicateController extends Controller
class PersonDuplicateController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
private $eventDispatcher;
/**
* @var \Chill\PersonBundle\Actions\Remove\PersonMove
*/
private $personMove;
/**
* @var \Chill\PersonBundle\Repository\PersonRepository
*/
private $personRepository;
/**
* @var \Chill\PersonBundle\Search\SimilarPersonMatcher
*/
private $similarPersonMatcher;
/**
* @var \Symfony\Component\Translation\TranslatorInterface
*/
private $translator;
public function __construct(
SimilarPersonMatcher $similarPersonMatcher,
TranslatorInterface $translator,
PersonRepository $personRepository,
PersonMove $personMove,
EventDispatcherInterface $eventDispatcher
) {
$this->similarPersonMatcher = $similarPersonMatcher;
$this->translator = $translator;
$this->personRepository = $personRepository;
$this->personMove = $personMove;
$this->eventDispatcher = $eventDispatcher;
public function __construct(private readonly SimilarPersonMatcher $similarPersonMatcher, private readonly TranslatorInterface $translator, private readonly PersonRepository $personRepository, private readonly PersonMove $personMove, private readonly EventDispatcherInterface $eventDispatcher)
{
}
public function confirmAction($person1_id, $person2_id, Request $request)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person1_id}/duplicate/{person2_id}/confirm", name="chill_person_duplicate_confirm")
*/
public function confirmAction(mixed $person1_id, mixed $person2_id, Request $request)
{
if ($person1_id === $person2_id) {
throw new InvalidArgumentException('Can not merge same person');
@@ -86,8 +52,7 @@ class PersonDuplicateController extends Controller
$person2->counters = $this->_getCounters($person2_id);
if (null === $person1) {
throw $this->createNotFoundException("Person with id {$person1_id} not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person1_id} not".' found on this server');
}
$this->denyAccessUnlessGranted(
@@ -97,8 +62,7 @@ class PersonDuplicateController extends Controller
);
if (null === $person2) {
throw $this->createNotFoundException("Person with id {$person2_id} not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person2_id} not".' found on this server');
}
$form = $this->createForm(PersonConfimDuplicateType::class);
@@ -111,7 +75,7 @@ class PersonDuplicateController extends Controller
'action' => 'move',
]);
$event->addPerson($person2);
$this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event);
$this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);
$sqls = $this->personMove->getSQL($person2, $person1);
@@ -127,20 +91,22 @@ class PersonDuplicateController extends Controller
return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
}
return $this->render('ChillPersonBundle:PersonDuplicate:confirm.html.twig', [
return $this->render('@ChillPerson/PersonDuplicate/confirm.html.twig', [
'person' => $person1,
'person2' => $person2,
'form' => $form->createView(),
]);
}
public function findManuallyDuplicateAction($person_id, Request $request)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/find-manually", name="chill_person_find_manually_duplicate")
*/
public function findManuallyDuplicateAction(mixed $person_id, Request $request)
{
$person = $this->_getPerson($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person_id} not".' found on this server');
}
$this->denyAccessUnlessGranted(
@@ -157,8 +123,7 @@ class PersonDuplicateController extends Controller
$person2 = $form->get('person')->getData();
if (null === $person2) {
throw $this->createNotFoundException("Person with id {$person2->getId}() not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person2->getId}() not".' found on this server');
}
$direction = $form->get('direction')->getData();
@@ -178,13 +143,16 @@ class PersonDuplicateController extends Controller
return $this->redirectToRoute('chill_person_duplicate_confirm', $params);
}
return $this->render('ChillPersonBundle:PersonDuplicate:find_manually.html.twig', [
return $this->render('@ChillPerson/PersonDuplicate/find_manually.html.twig', [
'person' => $person,
'form' => $form->createView(),
]);
}
public function notDuplicateAction($person1_id, $person2_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person1_id}/duplicate/{person2_id}/not-duplicate", name="chill_person_duplicate_not_duplicate")
*/
public function notDuplicateAction(mixed $person1_id, mixed $person2_id)
{
[$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id);
@@ -210,7 +178,10 @@ class PersonDuplicateController extends Controller
return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
}
public function removeNotDuplicateAction($person1_id, $person2_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person1_id}/duplicate/{person2_id}/remove-not-duplicate", name="chill_person_remove_duplicate_not_duplicate")
*/
public function removeNotDuplicateAction(mixed $person1_id, mixed $person2_id)
{
[$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id);
@@ -231,13 +202,15 @@ class PersonDuplicateController extends Controller
return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
}
public function viewAction($person_id, PersonNotDuplicateRepository $personNotDuplicateRepository)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/duplicate/view", name="chill_person_duplicate_view")
*/
public function viewAction(mixed $person_id, PersonNotDuplicateRepository $personNotDuplicateRepository)
{
$person = $this->_getPerson($person_id);
if (null === $person) {
throw $this->createNotFoundException("Person with id {$person_id} not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person_id} not".' found on this server');
}
$this->denyAccessUnlessGranted(
@@ -251,7 +224,7 @@ class PersonDuplicateController extends Controller
$notDuplicatePersons = $personNotDuplicateRepository->findNotDuplicatePerson($person);
return $this->render('ChillPersonBundle:PersonDuplicate:view.html.twig', [
return $this->render('@ChillPerson/PersonDuplicate/view.html.twig', [
'person' => $person,
'duplicatePersons' => $duplicatePersons,
'notDuplicatePersons' => $notDuplicatePersons,
@@ -269,20 +242,18 @@ class PersonDuplicateController extends Controller
$person = $em->getRepository(Person::class)->findOneBy(['id' => $id]);
return [
'nb_activity' => count($nb_activity),
'nb_document' => count($nb_document),
'nb_activity' => \count($nb_activity),
'nb_document' => \count($nb_document),
// 'nb_event' => count($nb_event),
'nb_task' => $nb_task,
'nb_addresses' => count($person->getAddresses()),
'nb_addresses' => \count($person->getAddresses()),
];
}
/**
* easy getting a person by his id.
*
* @param mixed $id
*/
private function _getPerson($id): ?Person
private function _getPerson(mixed $id): ?Person
{
return $this->personRepository->find($id);
}
@@ -302,13 +273,11 @@ class PersonDuplicateController extends Controller
}
if (null === $person1) {
throw $this->createNotFoundException("Person with id {$person1_id} not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person1_id} not".' found on this server');
}
if (null === $person2) {
throw $this->createNotFoundException("Person with id {$person2_id} not"
. ' found on this server');
throw $this->createNotFoundException("Person with id {$person2_id} not".' found on this server');
}
return [$person1, $person2];

View File

@@ -25,27 +25,14 @@ use Symfony\Contracts\Translation\TranslatorInterface;
final class PersonResourceController extends AbstractController
{
private EntityManagerInterface $em;
private PersonRepository $personRepository;
private PersonResourceRepository $personResourceRepository;
private TranslatorInterface $translator;
public function __construct(
PersonResourceRepository $personResourceRepository,
PersonRepository $personRepository,
EntityManagerInterface $em,
TranslatorInterface $translator
) {
$this->personResourceRepository = $personResourceRepository;
$this->personRepository = $personRepository;
$this->em = $em;
$this->translator = $translator;
public function __construct(private readonly PersonResourceRepository $personResourceRepository, private readonly PersonRepository $personRepository, private readonly EntityManagerInterface $em, private readonly TranslatorInterface $translator)
{
}
public function deleteAction(Request $request, $person_id, $resource_id): Response
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/resources/{resource_id}/delete", name="chill_person_resource_delete")
*/
public function deleteAction(Request $request, mixed $person_id, mixed $resource_id): Response
{
$personOwner = $this->personRepository->find($person_id);
$resource = $this->personResourceRepository->find($resource_id);
@@ -65,7 +52,7 @@ final class PersonResourceController extends AbstractController
->add('submit', SubmitType::class, ['label' => 'Delete'])
->getForm();
if ($request->getMethod() === Request::METHOD_DELETE) {
if (Request::METHOD_DELETE === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -82,7 +69,7 @@ final class PersonResourceController extends AbstractController
}
return $this->render(
'ChillPersonBundle:PersonResource:delete.html.twig',
'@ChillPerson/PersonResource/delete.html.twig',
[
'person' => $personOwner,
'resource' => $resource,
@@ -91,7 +78,10 @@ final class PersonResourceController extends AbstractController
);
}
public function editAction(Request $request, $resource_id, $person_id): Response
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/resources/{resource_id}/edit", name="chill_person_resource_edit")
*/
public function editAction(Request $request, mixed $resource_id, mixed $person_id): Response
{
$resource = $this->personResourceRepository->find($resource_id);
$personOwner = $this->personRepository->find($person_id);
@@ -115,7 +105,7 @@ final class PersonResourceController extends AbstractController
}
return $this->render(
'ChillPersonBundle:PersonResource:edit.html.twig',
'@ChillPerson/PersonResource/edit.html.twig',
[
'person' => $personOwner,
'resource' => $resource,
@@ -125,7 +115,10 @@ final class PersonResourceController extends AbstractController
);
}
public function listAction(Request $request, $person_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/resources/list", name="chill_person_resource_list")
*/
public function listAction(Request $request, mixed $person_id)
{
$personOwner = $this->personRepository->find($person_id);
$this->denyAccessUnlessGranted(PersonVoter::SEE, $personOwner);
@@ -134,7 +127,7 @@ final class PersonResourceController extends AbstractController
$personResources = $this->personResourceRepository->findBy(['personOwner' => $personOwner->getId()]);
return $this->render(
'ChillPersonBundle:PersonResource:list.html.twig',
'@ChillPerson/PersonResource/list.html.twig',
[
'person' => $personOwner,
'personResources' => $personResources,
@@ -142,7 +135,10 @@ final class PersonResourceController extends AbstractController
);
}
public function newAction(Request $request, $person_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/resources/new", name="chill_person_resource_new")
*/
public function newAction(Request $request, mixed $person_id)
{
$personOwner = $this->personRepository->find($person_id);
$personResource = new PersonResource();
@@ -164,7 +160,7 @@ final class PersonResourceController extends AbstractController
}
return $this->render(
'ChillPersonBundle:PersonResource:create.html.twig',
'@ChillPerson/PersonResource/create.html.twig',
[
'form' => $form->createView(),
'person' => $personOwner,

View File

@@ -33,53 +33,14 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Validator\Constraints\NotIdenticalTo;
use Symfony\Component\Validator\Constraints\NotNull;
use function is_int;
class ReassignAccompanyingPeriodController extends AbstractController
{
private AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository;
private AccompanyingPeriodRepository $courseRepository;
private EntityManagerInterface $em;
private EngineInterface $engine;
private FormFactoryInterface $formFactory;
private PaginatorFactory $paginatorFactory;
private Security $security;
private UserRender $userRender;
private UserRepository $userRepository;
public function __construct(
AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository,
UserRepository $userRepository,
AccompanyingPeriodRepository $courseRepository,
EngineInterface $engine,
FormFactoryInterface $formFactory,
PaginatorFactory $paginatorFactory,
Security $security,
UserRender $userRender,
EntityManagerInterface $em
) {
$this->accompanyingPeriodACLAwareRepository = $accompanyingPeriodACLAwareRepository;
$this->engine = $engine;
$this->formFactory = $formFactory;
$this->paginatorFactory = $paginatorFactory;
$this->security = $security;
$this->userRepository = $userRepository;
$this->userRender = $userRender;
$this->courseRepository = $courseRepository;
$this->em = $em;
public function __construct(private readonly AccompanyingPeriodACLAwareRepositoryInterface $accompanyingPeriodACLAwareRepository, private readonly UserRepository $userRepository, private readonly AccompanyingPeriodRepository $courseRepository, private readonly \Twig\Environment $engine, private readonly FormFactoryInterface $formFactory, private readonly PaginatorFactory $paginatorFactory, private readonly Security $security, private readonly UserRender $userRender, private readonly EntityManagerInterface $em)
{
}
/**
@@ -100,7 +61,7 @@ class ReassignAccompanyingPeriodController extends AbstractController
$total = $this->accompanyingPeriodACLAwareRepository->countByUserAndPostalCodesOpenedAccompanyingPeriod($userFrom, $postalCodes);
$paginator = $this->paginatorFactory->create($total);
$paginator->setItemsPerPage(50);
$paginator->setItemsPerPage(100);
$periods = $this->accompanyingPeriodACLAwareRepository
->findByUserAndPostalCodesOpenedAccompanyingPeriod(
$userFrom,
@@ -122,7 +83,8 @@ class ReassignAccompanyingPeriodController extends AbstractController
$assignForm->handleRequest($request);
if ($assignForm->isSubmitted() && $assignForm->isValid()) {
$assignPeriodIds = json_decode($assignForm->get('periods')->getData(), true, 512, JSON_THROW_ON_ERROR);
$assignPeriodIds = json_decode((string) $assignForm->get('periods')->getData(), true, 512, JSON_THROW_ON_ERROR);
/** @var User $userTo */
$userTo = $assignForm->get('userTo')->getData();
$userFrom = $assignForm->get('userFrom')->getData();
@@ -131,6 +93,10 @@ class ReassignAccompanyingPeriodController extends AbstractController
if ($period->getUser() === $userFrom) {
$period->setUser($userTo, true);
if (null !== $userTo->getUserJob() && $period->getJob() !== $userTo->getUserJob()) {
$period->setJob($userTo->getUserJob());
}
}
}
@@ -216,7 +182,7 @@ class ReassignAccompanyingPeriodController extends AbstractController
return null;
}
if (!is_int((int) $id)) {
if (!\is_int((int) $id)) {
throw new TransformationFailedException('the user id is not a numeric');
}

View File

@@ -21,14 +21,8 @@ use Symfony\Component\Validator\Validator\ValidatorInterface;
class RelationshipApiController extends ApiController
{
private RelationshipRepository $repository;
private ValidatorInterface $validator;
public function __construct(ValidatorInterface $validator, RelationshipRepository $repository)
public function __construct(private readonly ValidatorInterface $validator, private readonly RelationshipRepository $repository)
{
$this->validator = $validator;
$this->repository = $repository;
}
/**

View File

@@ -27,20 +27,8 @@ use Symfony\Contracts\Translation\TranslatorInterface;
final class ResidentialAddressController extends AbstractController
{
private UrlGeneratorInterface $generator;
private ResidentialAddressRepository $residentialAddressRepository;
private TranslatorInterface $translator;
public function __construct(
UrlGeneratorInterface $generator,
TranslatorInterface $translator,
ResidentialAddressRepository $residentialAddressRepository
) {
$this->generator = $generator;
$this->translator = $translator;
$this->residentialAddressRepository = $residentialAddressRepository;
public function __construct(private readonly UrlGeneratorInterface $generator, private readonly TranslatorInterface $translator, private readonly ResidentialAddressRepository $residentialAddressRepository)
{
}
/**

View File

@@ -13,7 +13,6 @@ namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use DateTimeImmutable;
use Symfony\Component\HttpFoundation\Request;
class SocialIssueApiController extends ApiController
@@ -26,7 +25,7 @@ class SocialIssueApiController extends ApiController
$query->expr()->isNull('e.desactivationDate')
)
);
$query->setParameter('now', new DateTimeImmutable());
$query->setParameter('now', new \DateTimeImmutable());
}
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)

View File

@@ -13,7 +13,6 @@ namespace Chill\PersonBundle\Controller\SocialWork;
use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use LogicException;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
@@ -29,7 +28,7 @@ class SocialIssueController extends CRUDController
return parent::createFormFor($action, $entity, $formClass, ['step' => 'edit']);
}
throw new LogicException('action is not supported: ' . $action);
throw new \LogicException('action is not supported: '.$action);
}
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)

View File

@@ -22,11 +22,8 @@ use Symfony\Component\Routing\Annotation\Route;
class SocialWorkEvaluationApiController extends AbstractController
{
private PaginatorFactory $paginatorFactory;
public function __construct(PaginatorFactory $paginatorFactory)
public function __construct(private readonly PaginatorFactory $paginatorFactory)
{
$this->paginatorFactory = $paginatorFactory;
}
/**
@@ -36,6 +33,7 @@ class SocialWorkEvaluationApiController extends AbstractController
* "_format": "json"
* }
* )
*
* @ParamConverter("action", options={"id": "action_id"})
*/
public function listEvaluationBySocialAction(SocialAction $action): Response

View File

@@ -21,14 +21,8 @@ use Symfony\Component\HttpFoundation\Response;
class SocialWorkGoalApiController extends ApiController
{
private GoalRepository $goalRepository;
private PaginatorFactory $paginator;
public function __construct(GoalRepository $goalRepository, PaginatorFactory $paginator)
public function __construct(private readonly GoalRepository $goalRepository, private readonly PaginatorFactory $paginator)
{
$this->goalRepository = $goalRepository;
$this->paginator = $paginator;
}
public function listBySocialAction(Request $request, SocialAction $action): Response

View File

@@ -21,11 +21,8 @@ use Symfony\Component\HttpFoundation\Response;
class SocialWorkResultApiController extends ApiController
{
private ResultRepository $resultRepository;
public function __construct(ResultRepository $resultRepository)
public function __construct(private readonly ResultRepository $resultRepository)
{
$this->resultRepository = $resultRepository;
}
public function listByGoal(Request $request, Goal $goal): Response

View File

@@ -20,8 +20,6 @@ use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use function count;
final class SocialWorkSocialActionApiController extends ApiController
{
public function __construct(
@@ -47,9 +45,9 @@ final class SocialWorkSocialActionApiController extends ApiController
usort($socialActions, static fn (SocialAction $sa, SocialAction $sb) => $sa->getOrdering() <=> $sb->getOrdering());
$pagination = $this->paginator->create(count($socialActions));
$pagination = $this->paginator->create(\count($socialActions));
// max one page
$pagination->setItemsPerPage(count($socialActions));
$pagination->setItemsPerPage(\count($socialActions));
$collection = new Collection($socialActions, $pagination);

View File

@@ -22,23 +22,14 @@ use Symfony\Component\HttpFoundation\Request;
class TimelinePersonController extends AbstractController
{
protected EventDispatcherInterface $eventDispatcher;
protected PaginatorFactory $paginatorFactory;
protected TimelineBuilder $timelineBuilder;
public function __construct(
EventDispatcherInterface $eventDispatcher,
TimelineBuilder $timelineBuilder,
PaginatorFactory $paginatorFactory
) {
$this->eventDispatcher = $eventDispatcher;
$this->timelineBuilder = $timelineBuilder;
$this->paginatorFactory = $paginatorFactory;
public function __construct(protected EventDispatcherInterface $eventDispatcher, protected TimelineBuilder $timelineBuilder, protected PaginatorFactory $paginatorFactory)
{
}
public function personAction(Request $request, $person_id)
/**
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/person/{person_id}/timeline", name="chill_person_timeline")
*/
public function personAction(Request $request, mixed $person_id)
{
$person = $this->getDoctrine()
->getRepository(Person::class)
@@ -58,10 +49,10 @@ class TimelinePersonController extends AbstractController
$paginator = $this->paginatorFactory->create($nbItems);
$event = new PrivacyEvent($person, ['action' => 'timeline']);
$this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event);
$this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);
return $this->render(
'ChillPersonBundle:Timeline:index.html.twig',
'@ChillPerson/Timeline/index.html.twig',
[
'timeline' => $this->timelineBuilder->getTimelineHTML(
'person',

View File

@@ -21,14 +21,8 @@ use Symfony\Component\Routing\Annotation\Route;
class UserAccompanyingPeriodController extends AbstractController
{
private AccompanyingPeriodRepository $accompanyingPeriodRepository;
private PaginatorFactory $paginatorFactory;
public function __construct(AccompanyingPeriodRepository $accompanyingPeriodRepository, PaginatorFactory $paginatorFactory)
public function __construct(private readonly AccompanyingPeriodRepository $accompanyingPeriodRepository, private readonly PaginatorFactory $paginatorFactory)
{
$this->accompanyingPeriodRepository = $accompanyingPeriodRepository;
$this->paginatorFactory = $paginatorFactory;
}
/**

View File

@@ -14,9 +14,6 @@ namespace Chill\PersonBundle\DataFixtures\Helper;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\EntityManagerInterface;
use function array_pop;
use function random_int;
trait PersonRandomHelper
{
private ?int $countPersons = null;
@@ -41,11 +38,11 @@ trait PersonRandomHelper
->select('p')
->from(Person::class, 'p')
->getQuery()
->setFirstResult(random_int(0, $this->countPersons - $fetchBy))
->setFirstResult(\random_int(0, $this->countPersons - $fetchBy))
->setMaxResults($fetchBy)
->getResult();
}
return array_pop($this->randPersons);
return \array_pop($this->randPersons);
}
}

View File

@@ -14,8 +14,6 @@ namespace Chill\PersonBundle\DataFixtures\Helper;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\EntityManagerInterface;
use function random_int;
trait RandomPersonHelperTrait
{
private ?int $nbOfPersons = null;
@@ -36,7 +34,7 @@ trait RandomPersonHelperTrait
return $qb
->select('p')
->setMaxResults(1)
->setFirstResult(random_int(0, $this->nbOfPersons))
->setFirstResult(\random_int(0, $this->nbOfPersons))
->getQuery()
->getSingleResult();
}

View File

@@ -58,7 +58,7 @@ class LoadAccompanyingPeriodClosingMotive extends AbstractFixture implements Ord
foreach (static::$closingMotives as $ref => $new) {
$motive = new ClosingMotive();
$motive->setName($new['name'])
->setActive(($new['active'] ?? true));
->setActive($new['active'] ?? true);
$manager->persist($motive);
$this->addReference($ref, $motive);

View File

@@ -21,11 +21,11 @@ use Doctrine\Persistence\ObjectManager;
*/
class LoadAccompanyingPeriodOrigin extends AbstractFixture implements OrderedFixtureInterface
{
public const ACCOMPANYING_PERIOD_ORIGIN = 'accompanying_period_origin';
final public const ACCOMPANYING_PERIOD_ORIGIN = 'accompanying_period_origin';
public static $references = [];
private $phoneCall = ['en' => 'phone call', 'fr' => 'appel téléphonique'];
private array $phoneCall = ['en' => 'phone call', 'fr' => 'appel téléphonique'];
public function getOrder()
{

View File

@@ -17,13 +17,8 @@ use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Chill\PersonBundle\Repository\AccompanyingPeriodRepository;
use Chill\PersonBundle\Repository\SocialWork\EvaluationRepository;
use DateTimeImmutable;
use Doctrine\Persistence\ObjectManager;
use function array_pop;
use function array_rand;
use function count;
class LoadAccompanyingPeriodWork extends \Doctrine\Bundle\FixturesBundle\Fixture implements \Doctrine\Common\DataFixtures\DependentFixtureInterface
{
/**
@@ -31,16 +26,8 @@ class LoadAccompanyingPeriodWork extends \Doctrine\Bundle\FixturesBundle\Fixture
*/
private array $cacheEvaluations = [];
private EvaluationRepository $evaluationRepository;
private AccompanyingPeriodRepository $periodRepository;
public function __construct(
AccompanyingPeriodRepository $periodRepository,
EvaluationRepository $evaluationRepository
) {
$this->periodRepository = $periodRepository;
$this->evaluationRepository = $evaluationRepository;
public function __construct(private readonly AccompanyingPeriodRepository $periodRepository, private readonly EvaluationRepository $evaluationRepository)
{
}
public function getDependencies()
@@ -58,8 +45,8 @@ class LoadAccompanyingPeriodWork extends \Doctrine\Bundle\FixturesBundle\Fixture
$i = 0;
while (null !== $period = array_pop($periods)) {
/** @var AccompanyingPeriod $period */
while (null !== $period = \array_pop($periods)) {
/* @var AccompanyingPeriod $period */
++$i;
if (0 === $i % 15) {
@@ -76,11 +63,11 @@ class LoadAccompanyingPeriodWork extends \Doctrine\Bundle\FixturesBundle\Fixture
$work
->setAccompanyingPeriod($period)
->setSocialAction($action)
->setStartDate(new DateTimeImmutable('today'))
->setStartDate(new \DateTimeImmutable('today'))
->addPerson($period->getPersons()->first())
->setCreatedAt(new DateTimeImmutable())
->setCreatedAt(new \DateTimeImmutable())
->setCreatedBy($this->getReference('center a_social'))
->setUpdatedAt(new DateTimeImmutable())
->setUpdatedAt(new \DateTimeImmutable())
->setUpdatedBy($this->getReference('center a_social'));
$manager->persist($work);
@@ -103,11 +90,11 @@ class LoadAccompanyingPeriodWork extends \Doctrine\Bundle\FixturesBundle\Fixture
$work
->setAccompanyingPeriod($period)
->setSocialAction($action)
->setStartDate(new DateTimeImmutable('today'))
->setStartDate(new \DateTimeImmutable('today'))
->addPerson($period->getPersons()->first())
->setCreatedAt(new DateTimeImmutable())
->setCreatedAt(new \DateTimeImmutable())
->setCreatedBy($this->getReference('center a_social'))
->setUpdatedAt(new DateTimeImmutable())
->setUpdatedAt(new \DateTimeImmutable())
->setUpdatedBy($this->getReference('center a_social'));
$manager->persist($work);
$ev = new AccompanyingPeriod\AccompanyingPeriodWorkEvaluation();
@@ -124,20 +111,20 @@ class LoadAccompanyingPeriodWork extends \Doctrine\Bundle\FixturesBundle\Fixture
{
$actions = $socialIssue->getRecursiveSocialActions()->toArray();
if (0 === count($actions)) {
if (0 === \count($actions)) {
return null;
}
return $actions[array_rand($actions)];
return $actions[\array_rand($actions)];
}
private function getRandomEvaluation(): Evaluation
{
if (0 === count($this->cacheEvaluations)) {
if (0 === \count($this->cacheEvaluations)) {
$this->cacheEvaluations = $this->evaluationRepository
->findAll();
}
return $this->cacheEvaluations[array_rand($this->cacheEvaluations)];
return $this->cacheEvaluations[\array_rand($this->cacheEvaluations)];
}
}

View File

@@ -17,57 +17,30 @@ use Chill\CustomFieldsBundle\CustomFields\CustomFieldTitle;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Chill\CustomFieldsBundle\Entity\CustomFieldsDefaultGroup;
use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\Person;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectManager;
use RuntimeException;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class LoadCustomFields extends AbstractFixture implements
ContainerAwareInterface,
OrderedFixtureInterface
class LoadCustomFields extends AbstractFixture implements OrderedFixtureInterface
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @var CustomField
*/
private $customFieldChoice;
/**
* @var CustomField
*/
private $customFieldText;
/**
* @var TranslatableStringHelper
*/
private $translatableStringHelper;
/**
* @var TranslatorInterface
*/
private $translator;
private ?CustomField $cfText = null;
private ?CustomField $cfChoice = null;
/**
* /**
* LoadCustomFields constructor.
*/
public function __construct(
TranslatableStringHelper $translatableStringHelper,
TranslatorInterface $translator
private readonly EntityManagerInterface $entityManager,
private readonly CustomFieldChoice $customFieldChoice,
private readonly CustomFieldText $customFieldText,
) {
$this->translatableStringHelper = $translatableStringHelper;
$this->translator = $translator;
}
//put your code here
// put your code here
public function getOrder()
{
return 10003;
@@ -80,57 +53,40 @@ class LoadCustomFields extends AbstractFixture implements
$manager->flush();
}
public function setContainer(?ContainerInterface $container = null)
{
if (null === $container) {
throw new RuntimeException('The given container should not be null');
}
$this->container = $container;
}
private function createCustomFieldChoice()
{
return new CustomFieldChoice(
$this->translator,
$this->container->get('templating'),
$this->translatableStringHelper
);
return $this->customFieldChoice;
}
private function createCustomFieldText()
{
return new CustomFieldText(
$this->container->get('request_stack'),
$this->container->get('templating'),
$this->translatableStringHelper
);
return $this->customFieldText;
}
private function loadData(ObjectManager $manager)
{
$personIds = $this->container->get('doctrine.orm.entity_manager')
$personIds = $this->entityManager
->createQuery('SELECT person.id FROM ChillPersonBundle:Person person')
->getScalarResult();
// get possible values for cfGroup
$choices = array_map(
static fn ($a) => $a['slug'],
$this->customFieldChoice->getOptions()['choices']
$this->cfChoice->getOptions()['choices']
);
// create faker
$faker = \Faker\Factory::create('fr_FR');
// select a set of people and add data
foreach ($personIds as $id) {
// add info on 1 person on 2
if (random_int(0, 1) === 1) {
if (1 === random_int(0, 1)) {
/** @var Person $person */
$person = $manager->getRepository(Person::class)->find($id);
$person->setCFData([
'remarques' => $this->createCustomFieldText()
->serialize($faker->text(random_int(150, 250)), $this->customFieldText),
->serialize($faker->text(random_int(150, 250)), $this->cfText),
'document-d-identite' => $this->createCustomFieldChoice()
->serialize([$choices[array_rand($choices)]], $this->customFieldChoice),
->serialize([$choices[array_rand($choices)]], $this->cfChoice),
]);
}
}
@@ -162,7 +118,7 @@ class LoadCustomFields extends AbstractFixture implements
$manager->persist($customField0);
// create text field
$this->customFieldText = (new CustomField())
$this->cfText = $customFieldText = (new CustomField())
->setActive(true)
->setName(['fr' => 'Remarques'])
->setSlug('remarques')
@@ -170,10 +126,10 @@ class LoadCustomFields extends AbstractFixture implements
->setType('text')
->setOptions(['maxLength' => 5000])
->setCustomFieldsGroup($cfGroup);
$manager->persist($this->customFieldText);
$manager->persist($customFieldText);
// create choice field
$this->customFieldChoice = (new CustomField())
$this->cfChoice = $customFieldChoice = (new CustomField())
->setActive(true)
->setName(['fr' => "Document d'identité"])
->setSlug('document-d-identite')
@@ -204,6 +160,6 @@ class LoadCustomFields extends AbstractFixture implements
],
],
]);
$manager->persist($this->customFieldChoice);
$manager->persist($customFieldChoice);
}
}

View File

@@ -19,36 +19,22 @@ use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Person\PersonCenterHistory;
use Chill\PersonBundle\Household\MembersEditorFactory;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectManager;
use Nelmio\Alice\Loader\NativeLoader;
use function array_pop;
use function array_rand;
use function random_int;
use function shuffle;
class LoadHousehold extends Fixture implements DependentFixtureInterface
{
private const NUMBER_OF_HOUSEHOLD = 10;
private MembersEditorFactory $editorFactory;
private EntityManagerInterface $em;
private NativeLoader $loader;
private readonly NativeLoader $loader;
private array $personIds;
public function __construct(MembersEditorFactory $editorFactory, EntityManagerInterface $em)
public function __construct(private readonly MembersEditorFactory $editorFactory, private readonly EntityManagerInterface $em)
{
$this->editorFactory = $editorFactory;
$this->em = $em;
$this->loader = new NativeLoader();
}
@@ -70,43 +56,43 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
$this->generateHousehold(
$manager,
DateTimeImmutable::createFromFormat('Y-m-d', '2010-01-01')
\DateTimeImmutable::createFromFormat('Y-m-d', '2010-01-01')
);
$this->preparePersonIds();
$this->generateHousehold(
$manager,
DateTimeImmutable::createFromFormat('Y-m-d', '2015-01-01')
\DateTimeImmutable::createFromFormat('Y-m-d', '2015-01-01')
);
$manager->flush();
}
private function addAddressToHousehold(Household $household, DateTimeImmutable $date, ObjectManager $manager)
private function addAddressToHousehold(Household $household, \DateTimeImmutable $date, ObjectManager $manager)
{
if (random_int(0, 10) > 8) {
if (\random_int(0, 10) > 8) {
// 20% of household without address
return;
}
$nb = random_int(1, 6);
$nb = \random_int(1, 6);
$i = 0;
while ($i < $nb) {
$address = $this->createAddress();
$address->setValidFrom(DateTime::createFromImmutable($date));
$address->setValidFrom(\DateTime::createFromImmutable($date));
if (random_int(0, 20) < 1) {
$date = $date->add(new DateInterval('P' . random_int(8, 52) . 'W'));
$address->setValidTo(DateTime::createFromImmutable($date));
if (\random_int(0, 20) < 1) {
$date = $date->add(new \DateInterval('P'.\random_int(8, 52).'W'));
$address->setValidTo(\DateTime::createFromImmutable($date));
}
$household->addAddress($address);
$manager->persist($address);
$date = $date->add(new DateInterval('P' . random_int(8, 52) . 'W'));
$date = $date->add(new \DateInterval('P'.\random_int(8, 52).'W'));
++$i;
}
}
@@ -126,7 +112,7 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
return $objectSet->getObjects()['address1'];
}
private function generateHousehold(ObjectManager $manager, DateTimeImmutable $startDate)
private function generateHousehold(ObjectManager $manager, \DateTimeImmutable $startDate)
{
for ($i = 0; self::NUMBER_OF_HOUSEHOLD > $i; ++$i) {
$household = new Household();
@@ -140,7 +126,7 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
$k = 0;
foreach ($this->getRandomPersons(1, 3) as $person) {
$date = $startDate->add(new DateInterval('P' . random_int(1, 200) . 'W'));
$date = $startDate->add(new \DateInterval('P'.\random_int(1, 200).'W'));
$position = $this->getReference(LoadHouseholdPosition::ADULT);
$movement->addMovement($date, $person, $position, 0 === $k, 'self generated');
@@ -149,7 +135,7 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
// load children
foreach ($this->getRandomPersons(0, 3) as $person) {
$date = $startDate->add(new DateInterval('P' . random_int(1, 200) . 'W'));
$date = $startDate->add(new \DateInterval('P'.\random_int(1, 200).'W'));
$position = $this->getReference(LoadHouseholdPosition::CHILD);
$movement->addMovement($date, $person, $position, 0 === $k, 'self generated');
@@ -158,7 +144,7 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
// load children out
foreach ($this->getRandomPersons(0, 2) as $person) {
$date = $startDate->add(new DateInterval('P' . random_int(1, 200) . 'W'));
$date = $startDate->add(new \DateInterval('P'.\random_int(1, 200).'W'));
$position = $this->getReference(LoadHouseholdPosition::CHILD_OUT);
$movement->addMovement($date, $person, $position, 0 === $k, 'self generated');
@@ -173,7 +159,7 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
private function getPostalCode(): PostalCode
{
$ref = LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)];
$ref = LoadPostalCodes::$refs[\array_rand(LoadPostalCodes::$refs)];
return $this->getReference($ref);
}
@@ -182,10 +168,10 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
{
$persons = [];
$nb = random_int($min, $max);
$nb = \random_int($min, $max);
for ($i = 0; $i < $nb; ++$i) {
$personId = array_pop($this->personIds)['id'];
$personId = \array_pop($this->personIds)['id'];
$persons[] = $this->em->getRepository(Person::class)->find($personId);
}
@@ -199,17 +185,17 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
// @TODO: Remove this and make this service stateless
$this->personIds = $this->em
->createQuery(
'SELECT p.id FROM ' . Person::class . ' p ' .
'WHERE EXISTS( ' .
'SELECT 1 FROM ' . PersonCenterHistory::class . ' pch ' .
'JOIN pch.center c ' .
'WHERE pch.person = p.id ' .
'AND c.name IN (:authorized_centers)' .
'SELECT p.id FROM '.Person::class.' p '.
'WHERE EXISTS( '.
'SELECT 1 FROM '.PersonCenterHistory::class.' pch '.
'JOIN pch.center c '.
'WHERE pch.person = p.id '.
'AND c.name IN (:authorized_centers)'.
')'
)
->setParameter('authorized_centers', $centers)
->getScalarResult();
shuffle($this->personIds);
\shuffle($this->personIds);
}
}

View File

@@ -18,7 +18,7 @@ use Doctrine\Persistence\ObjectManager;
class LoadHouseholdCompositionType extends AbstractFixture implements FixtureGroupInterface
{
public const TYPES = [
final public const TYPES = [
['fr' => 'Couple avec enfant(s)'],
['fr' => 'Couple sans enfant'],
['fr' => 'Mère seule'],

View File

@@ -17,13 +17,13 @@ use Doctrine\Persistence\ObjectManager;
class LoadHouseholdPosition extends Fixture
{
public const ADULT = 'position_adulte';
final public const ADULT = 'position_adulte';
public const CHILD = 'position_enfant';
final public const CHILD = 'position_enfant';
public const CHILD_OUT = 'position_enfant_hors';
final public const CHILD_OUT = 'position_enfant_hors';
public const POSITIONS_DATA = [
final public const POSITIONS_DATA = [
['Adulte', true, true, 1.0, self::ADULT],
['Enfant', true, false, 2.0, self::CHILD],
['Enfant hors ménage', false, false, 3.0, self::CHILD_OUT],

View File

@@ -21,7 +21,7 @@ use Doctrine\Persistence\ObjectManager;
*/
class LoadMaritalStatus extends AbstractFixture implements OrderedFixtureInterface
{
private $maritalStatuses = [
private array $maritalStatuses = [
['id' => 'single', 'name' => ['en' => 'single', 'fr' => 'célibataire']],
['id' => 'married', 'name' => ['en' => 'married', 'fr' => 'marié(e)']],
['id' => 'widow', 'name' => ['en' => 'widow', 'fr' => 'veuf veuve ']],
@@ -41,11 +41,11 @@ class LoadMaritalStatus extends AbstractFixture implements OrderedFixtureInterfa
echo "loading maritalStatuses... \n";
foreach ($this->maritalStatuses as $ms) {
echo $ms['name']['en'] . ' ';
echo $ms['name']['en'].' ';
$new_ms = new MaritalStatus();
$new_ms->setId($ms['id']);
$new_ms->setName($ms['name']);
$this->addReference('ms_' . $ms['id'], $new_ms);
$this->addReference('ms_'.$ms['id'], $new_ms);
$manager->persist($new_ms);
}

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\DataFixtures\ORM;
use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes;
use Chill\MainBundle\Doctrine\Model\Point;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Country;
@@ -29,13 +28,9 @@ use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Chill\PersonBundle\Repository\MaritalStatusRepository;
use Chill\PersonBundle\Repository\SocialWork\SocialIssueRepository;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Exception;
use Faker\Factory;
use Faker\Generator;
use Nelmio\Alice\Loader\NativeLoader;
@@ -43,10 +38,6 @@ use Nelmio\Alice\ObjectSet;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\Workflow\Registry;
use function count;
use function random_int;
use function ucfirst;
/**
* Load people into database.
*/
@@ -54,7 +45,7 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
{
use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
public const PERSON = 'person';
final public const PERSON = 'person';
/**
* @var array|Center[]
@@ -86,27 +77,13 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
*/
protected array $cacheUsers = [];
protected CenterRepository $centerRepository;
protected CountryRepository $countryRepository;
protected Generator $faker;
protected NativeLoader $loader;
protected MaritalStatusRepository $maritalStatusRepository;
private array $genders = [Person::MALE_GENDER, Person::FEMALE_GENDER, Person::BOTH_GENDER];
protected ScopeRepository $scopeRepository;
protected SocialIssueRepository $socialIssueRepository;
protected UserRepository $userRepository;
protected Registry $workflowRegistry;
private $genders = [Person::MALE_GENDER, Person::FEMALE_GENDER, Person::BOTH_GENDER];
private $peoples = [
private array $peoples = [
[
'lastName' => 'Depardieu',
'firstName' => 'Gérard',
@@ -132,7 +109,7 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
],
],
[
//to have a person with same firstname as Gérard Depardieu
// to have a person with same firstname as Gérard Depardieu
'lastName' => 'Depardieu',
'firstName' => 'Jean',
'birthdate' => '1960-10-12',
@@ -142,7 +119,7 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
'maritalStatus' => 'ms_divorce',
],
[
//to have a person with same birthdate of Gérard Depardieu
// to have a person with same birthdate of Gérard Depardieu
'lastName' => 'Van Snick',
'firstName' => 'Bart',
'birthdate' => '1948-12-27',
@@ -150,22 +127,23 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
'maritalStatus' => 'ms_legalco',
],
[
//to have a woman with Depardieu as FirstName
// to have a woman with Depardieu as FirstName
'lastName' => 'Depardieu',
'firstName' => 'Charline',
'birthdate' => '1970-10-15',
'gender' => Person::FEMALE_GENDER,
'center' => 'Center A',
'maritalStatus' => 'ms_legalco',
],
[
//to have a special character in lastName
// to have a special character in lastName
'lastName' => 'Manço',
'firstName' => 'Étienne',
'center' => 'Center A',
'maritalStatus' => 'ms_unknown',
],
[
//to have true duplicate person
// to have true duplicate person
'lastName' => 'Depardieu',
'firstName' => 'Jean',
'birthdate' => '1960-10-12',
@@ -175,7 +153,7 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
'maritalStatus' => 'ms_divorce',
],
[
//to have false duplicate person
// to have false duplicate person
'lastName' => 'Depardieu',
'firstName' => 'Jeanne',
'birthdate' => '1966-11-13',
@@ -243,24 +221,17 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
];
public function __construct(
Registry $workflowRegistry,
SocialIssueRepository $socialIssueRepository,
CenterRepository $centerRepository,
CountryRepository $countryRepository,
MaritalStatusRepository $maritalStatusRepository,
ScopeRepository $scopeRepository,
UserRepository $userRepository
protected Registry $workflowRegistry,
protected SocialIssueRepository $socialIssueRepository,
protected CenterRepository $centerRepository,
protected CountryRepository $countryRepository,
protected MaritalStatusRepository $maritalStatusRepository,
protected ScopeRepository $scopeRepository,
protected UserRepository $userRepository
) {
$this->faker = Factory::create('fr_FR');
$this->faker->addProvider($this);
$this->workflowRegistry = $workflowRegistry;
$this->socialIssueRepository = $socialIssueRepository;
$this->centerRepository = $centerRepository;
$this->countryRepository = $countryRepository;
$this->maritalStatusRepository = $maritalStatusRepository;
$this->loader = new NativeLoader($this->faker);
$this->scopeRepository = $scopeRepository;
$this->userRepository = $userRepository;
}
public function getOrder()
@@ -273,7 +244,7 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
*/
public function getRandomCenter(): Center
{
if (0 === count($this->cacheCenters)) {
if (0 === \count($this->cacheCenters)) {
$this->cacheCenters = $this->centerRepository->findAll();
}
@@ -283,15 +254,15 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
/**
* @internal This method is public and called by faker as a custom generator
*
* @throws Exception
* @throws \Exception
*/
public function getRandomCountry(int $nullPercentage = 20): ?Country
{
if (0 === count($this->cacheCountries)) {
if (0 === \count($this->cacheCountries)) {
$this->cacheCountries = $this->countryRepository->findAll();
}
if (random_int(0, 100) > $nullPercentage) {
if (\random_int(0, 100) > $nullPercentage) {
return null;
}
@@ -309,15 +280,15 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
/**
* @internal This method is public and called by faker as a custom generator
*
* @throws Exception
* @throws \Exception
*/
public function getRandomMaritalStatus(int $nullPercentage = 50): ?MaritalStatus
{
if (0 === count($this->cacheMaritalStatuses)) {
if (0 === \count($this->cacheMaritalStatuses)) {
$this->cacheMaritalStatuses = $this->maritalStatusRepository->findAll();
}
if (random_int(0, 100) > $nullPercentage) {
if (\random_int(0, 100) > $nullPercentage) {
return null;
}
@@ -355,22 +326,22 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
/**
* create a new person from array data.
*
* @throws Exception
* @throws \Exception
*/
private function addAPerson(Person $person, ObjectManager $manager)
{
$accompanyingPeriod = new AccompanyingPeriod(
(new DateTime())
(new \DateTime())
->sub(
new DateInterval('P' . random_int(0, 180) . 'D')
new \DateInterval('P'.\random_int(0, 180).'D')
)
);
$accompanyingPeriod->setCreatedBy($this->getRandomUser())
->setCreatedAt(new DateTimeImmutable('now'));
->setCreatedAt(new \DateTimeImmutable('now'));
$person->addAccompanyingPeriod($accompanyingPeriod);
$accompanyingPeriod->addSocialIssue($this->getRandomSocialIssue());
if (random_int(0, 10) > 3) {
if (\random_int(0, 10) > 3) {
// always add social scope:
$accompanyingPeriod->addScope($this->getReference('scope_social'));
$origin = $this->getReference(LoadAccompanyingPeriodOrigin::ACCOMPANYING_PERIOD_ORIGIN);
@@ -384,9 +355,8 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
$manager->persist($person);
$manager->persist($accompanyingPeriod);
echo "add person'" . $person->__toString() . "'\n";
$this->addReference(self::PERSON . $person->getId(), $person);
$this->addReference(self::PERSON.$person->getId(), $person);
}
private function createAddress(): Address
@@ -429,7 +399,7 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
foreach ($default as $key => $value) {
switch ($key) {
case 'birthdate':
$person->setBirthdate(new DateTime($value));
$person->setBirthdate(new \DateTime($value));
break;
@@ -492,7 +462,7 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
private function getRandomSocialIssue(): SocialIssue
{
if (0 === count($this->cacheSocialIssues)) {
if (0 === \count($this->cacheSocialIssues)) {
$this->cacheSocialIssues = $this->socialIssueRepository->findAll();
}
@@ -501,29 +471,10 @@ class LoadPeople extends AbstractFixture implements ContainerAwareInterface, Ord
private function getRandomUser(): User
{
if (0 === count($this->cacheUsers)) {
if (0 === \count($this->cacheUsers)) {
$this->cacheUsers = $this->userRepository->findAll();
}
return $this->cacheUsers[array_rand($this->cacheUsers)];
}
/*
private function addAccompanyingPeriods(Person $person, array $periods, ObjectManager $manager)
{
foreach ($periods as $period) {
echo "adding new past Accompanying Period..\n";
/** @var AccompanyingPeriod $accompanyingPeriod
$accompanyingPeriod = new AccompanyingPeriod(new \DateTime($period['from']));
$accompanyingPeriod
->setClosingDate(new \DateTime($period['to']))
->setRemark($period['remark'])
;
$person->addAccompanyingPeriod($accompanyingPeriod);
}
}
*/
}

View File

@@ -36,12 +36,10 @@ class LoadPersonACL extends AbstractFixture implements OrderedFixtureInterface
$permissionsGroup = $this->getReference($permissionsGroupRef);
$scopeSocial = $this->getReference('scope_social');
//create permission group
// create permission group
switch ($permissionsGroup->getName()) {
case 'social':
case 'direction':
printf("Adding CHILL_PERSON_UPDATE & CHILL_PERSON_CREATE to %s permission group \n", $permissionsGroup->getName());
$permissionsGroup->addRoleScope(
(new RoleScope())
->setRole(AccompanyingPeriodVoter::FULL)
@@ -80,7 +78,6 @@ class LoadPersonACL extends AbstractFixture implements OrderedFixtureInterface
break;
case 'administrative':
printf("Adding CHILL_PERSON_SEE to %s permission group \n", $permissionsGroup->getName());
$roleScopeSee = (new RoleScope())
->setRole('CHILL_PERSON_SEE')
->setScope(null);

View File

@@ -18,9 +18,9 @@ use Doctrine\Persistence\ObjectManager;
class LoadRelations extends Fixture implements FixtureGroupInterface
{
public const RELATION_KEY = 'relations';
final public const RELATION_KEY = 'relations';
public const RELATIONS = [
final public const RELATIONS = [
['title' => ['fr' => 'Parent'], 'reverseTitle' => ['fr' => 'Enfant']],
['title' => ['fr' => 'En couple'], 'reverseTitle' => ['fr' => 'En couple']],
['title' => ['fr' => 'Beau parent'], 'reverseTitle' => ['fr' => 'Belle-fille·beau-fils']],
@@ -38,13 +38,13 @@ class LoadRelations extends Fixture implements FixtureGroupInterface
public function load(ObjectManager $manager)
{
foreach (self::RELATIONS as $key => $value) {
echo 'Creating a new relation type: relation' . $value['title']['fr'] . 'reverse relation: ' . $value['reverseTitle']['fr'] . "\n";
echo 'Creating a new relation type: relation'.$value['title']['fr'].'reverse relation: '.$value['reverseTitle']['fr']."\n";
$relation = new Relation();
$relation->setTitle($value['title'])
->setReverseTitle($value['reverseTitle']);
$manager->persist($relation);
$this->addReference(self::RELATION_KEY . $key, $relation);
$this->addReference(self::RELATION_KEY.$key, $relation);
}
$manager->flush();

View File

@@ -15,24 +15,17 @@ use Chill\MainBundle\DataFixtures\ORM\LoadUsers;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\DataFixtures\Helper\PersonRandomHelper;
use Chill\PersonBundle\Entity\Relationships\Relationship;
use DateTimeImmutable;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectManager;
use function array_key_exists;
use function count;
class LoadRelationships extends Fixture implements DependentFixtureInterface
{
use PersonRandomHelper;
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
public function __construct(private readonly EntityManagerInterface $em)
{
$this->em = $em;
}
public function getDependencies(): array
@@ -45,16 +38,17 @@ class LoadRelationships extends Fixture implements DependentFixtureInterface
public function load(ObjectManager $manager): void
{
/** @var array<int, array<int, 1>> $existing */
$existing = [];
for ($i = 0; 20 > $i; ++$i) {
$user = $this->getRandomUser();
$date = new DateTimeImmutable();
$date = new \DateTimeImmutable();
$relationship = (new Relationship())
->setFromPerson($this->getRandomPerson($this->em))
->setToPerson($this->getRandomPerson($this->em))
->setRelation($this->getReference(LoadRelations::RELATION_KEY .
random_int(0, count(LoadRelations::RELATIONS) - 1)))
->setRelation($this->getReference(LoadRelations::RELATION_KEY.
random_int(0, \count(LoadRelations::RELATIONS) - 1)))
->setReverse((bool) random_int(0, 1))
->setCreatedBy($user)
->setUpdatedBy($user)
@@ -62,15 +56,16 @@ class LoadRelationships extends Fixture implements DependentFixtureInterface
->setUpdatedAt($date);
// remove the potential duplicates
$set = $relationship->getFromPerson()->getId() < $relationship->getToPerson()->getId() ?
[$relationship->getFromPerson()->getId(), $relationship->getToPerson()->getId()] :
[$relationship->getToPerson()->getId(), $relationship->getFromPerson()->getId()];
$set = [
min($relationship->getFromPerson()->getId(), $relationship->getToPerson()->getId()),
max($relationship->getFromPerson()->getId(), $relationship->getToPerson()->getId()),
];
if (array_key_exists($set[0], $existing) && array_key_exists($set[1], $existing[$set[0]])) {
if (\array_key_exists($set[0], $existing) && \array_key_exists($set[1], $existing[$set[0]])) {
continue;
}
$existing[$set[0]][$set[1]] = 1;
$existing[$set[0]][$existing[$set[1]]] = 1;
$manager->persist($relationship);
}

View File

@@ -15,17 +15,12 @@ use Chill\PersonBundle\Service\Import\SocialWorkMetadata;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Exception;
use League\Csv\Reader;
use Throwable;
class LoadSocialWorkMetadata extends Fixture implements OrderedFixtureInterface
{
private SocialWorkMetadata $importer;
public function __construct(SocialWorkMetadata $importer)
public function __construct(private readonly SocialWorkMetadata $importer)
{
$this->importer = $importer;
}
public function getOrder()
@@ -36,9 +31,9 @@ class LoadSocialWorkMetadata extends Fixture implements OrderedFixtureInterface
public function load(ObjectManager $manager)
{
try {
$csv = Reader::createFromPath(__DIR__ . '/data/social_work_metadata.csv');
} catch (Throwable $e) {
throw new Exception('Error while loading CSV.', 0, $e);
$csv = Reader::createFromPath(__DIR__.'/data/social_work_metadata.csv');
} catch (\Throwable $e) {
throw new \Exception('Error while loading CSV.', 0, $e);
}
$csv->setDelimiter(';');

View File

@@ -20,7 +20,6 @@ use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodCommentVoter;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodResourceVoter;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Exception;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
@@ -28,8 +27,6 @@ use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use function array_key_exists;
/**
* Class ChillPersonExtension
* Loads and manages your bundle configuration.
@@ -39,7 +36,7 @@ use function array_key_exists;
class ChillPersonExtension extends Extension implements PrependExtensionInterface
{
/**
* @throws Exception
* @throws \Exception
*/
public function load(array $configs, ContainerBuilder $container)
{
@@ -73,7 +70,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
// register all configuration in a unique parameter
$container->setParameter('chill_person', $config);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../config'));
$loader->load('services.yaml');
$loader->load('services/widgets.yaml');
$loader->load('services/fixtures.yaml');
@@ -97,10 +94,11 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
$loader->load('services/exports_person.yaml');
if ($container->getParameter('chill_person.accompanying_period') !== 'hidden') {
if ('hidden' !== $container->getParameter('chill_person.accompanying_period')) {
$loader->load('services/exports_accompanying_course.yaml');
$loader->load('services/exports_social_actions.yaml');
$loader->load('services/exports_evaluation.yaml');
$loader->load('services/exports_accompanying_period_step_history.yaml');
}
$loader->load('services/exports_household.yaml');
@@ -117,7 +115,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
$this->prependCruds($container);
$this->prependWorkflows($container);
//add person_fields parameter as global
// add person_fields parameter as global
$chillPersonConfig = $container->getExtensionConfig($this->getAlias());
$config = $this->processConfiguration(new Configuration(), $chillPersonConfig);
$twigConfig = [
@@ -129,13 +127,13 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
'fields' => $config['accompanying_periods_fields'],
],
],
'form_themes' => ['ChillPersonBundle:Export:ListPersonFormFields.html.twig'],
'form_themes' => ['@ChillPerson/Export/ListPersonFormFields.html.twig'],
];
$container->prependExtensionConfig('twig', $twigConfig);
$this->declarePersonAsCustomizable($container);
//declare routes for person bundle
// declare routes for person bundle
$container->prependExtensionConfig('chill_main', [
'routing' => [
'resources' => [
@@ -150,7 +148,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
$container->prependExtensionConfig('chill_main', [
'cruds' => [
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive::class,
'class' => AccompanyingPeriod\ClosingMotive::class,
'name' => 'closing_motive',
'base_path' => '/admin/person/closing-motive',
'form_class' => \Chill\PersonBundle\Form\ClosingMotiveType::class,
@@ -171,7 +169,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
],
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Origin::class,
'class' => AccompanyingPeriod\Origin::class,
'name' => 'origin',
'base_path' => '/admin/person/origin',
'form_class' => \Chill\PersonBundle\Form\OriginType::class,
@@ -404,16 +402,16 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
'apis' => [
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod::class,
'class' => AccompanyingPeriod::class,
'name' => 'accompanying_course',
'base_path' => '/api/1.0/person/accompanying-course',
'controller' => \Chill\PersonBundle\Controller\AccompanyingCourseApiController::class,
'actions' => [
'_entity' => [
'roles' => [
Request::METHOD_GET => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_PATCH => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_PUT => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_GET => AccompanyingPeriodVoter::SEE,
Request::METHOD_PATCH => AccompanyingPeriodVoter::SEE,
Request::METHOD_PUT => AccompanyingPeriodVoter::SEE,
],
'methods' => [
Request::METHOD_GET => true,
@@ -429,8 +427,8 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
Request::METHOD_HEAD => false,
],
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => AccompanyingPeriodVoter::SEE,
],
],
'resource' => [
@@ -441,8 +439,8 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
Request::METHOD_HEAD => false,
],
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => AccompanyingPeriodVoter::SEE,
],
],
'comment' => [
@@ -453,8 +451,8 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
Request::METHOD_HEAD => false,
],
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => AccompanyingPeriodVoter::SEE,
],
],
'requestor' => [
@@ -465,8 +463,8 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
Request::METHOD_HEAD => false,
],
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => AccompanyingPeriodVoter::SEE,
],
],
'scope' => [
@@ -477,8 +475,8 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
Request::METHOD_HEAD => false,
],
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => AccompanyingPeriodVoter::SEE,
],
],
'socialissue' => [
@@ -490,8 +488,8 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
'controller_action' => 'socialIssueApi',
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => AccompanyingPeriodVoter::SEE,
],
],
'work' => [
@@ -503,7 +501,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
'controller_action' => 'workApi',
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE => 'ALWAYS_FAILS',
],
],
@@ -514,7 +512,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
Request::METHOD_HEAD => false,
],
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_POST => AccompanyingPeriodVoter::SEE,
],
],
// 'confidential' => [
@@ -538,7 +536,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
],
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Comment::class,
'class' => AccompanyingPeriod\Comment::class,
'name' => 'accompanying_period_comment',
'base_path' => '/api/1.0/person/accompanying-period/comment',
'base_role' => 'ROLE_USER',
@@ -557,7 +555,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
],
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Resource::class,
'class' => AccompanyingPeriod\Resource::class,
'name' => 'accompanying_period_resource',
'base_path' => '/api/1.0/person/accompanying-period/resource',
'base_role' => 'ROLE_USER',
@@ -576,7 +574,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
],
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Origin::class,
'class' => AccompanyingPeriod\Origin::class,
'name' => 'accompanying_period_origin',
'base_path' => '/api/1.0/person/accompanying-period/origin',
'controller' => \Chill\PersonBundle\Controller\OpeningApiController::class,
@@ -621,7 +619,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
'class' => \Chill\PersonBundle\Entity\Person::class,
'name' => 'person',
'base_path' => '/api/1.0/person/person',
'base_role' => \Chill\PersonBundle\Security\Authorization\PersonVoter::SEE,
'base_role' => PersonVoter::SEE,
'controller' => \Chill\PersonBundle\Controller\PersonApiController::class,
'actions' => [
'_entity' => [
@@ -632,10 +630,10 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
Request::METHOD_PATCH => true,
],
'roles' => [
Request::METHOD_GET => \Chill\PersonBundle\Security\Authorization\PersonVoter::SEE,
Request::METHOD_HEAD => \Chill\PersonBundle\Security\Authorization\PersonVoter::SEE,
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\PersonVoter::CREATE,
Request::METHOD_PATCH => \Chill\PersonBundle\Security\Authorization\PersonVoter::CREATE,
Request::METHOD_GET => PersonVoter::SEE,
Request::METHOD_HEAD => PersonVoter::SEE,
Request::METHOD_POST => PersonVoter::CREATE,
Request::METHOD_PATCH => PersonVoter::CREATE,
],
],
'address' => [
@@ -721,7 +719,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
],
],
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWork::class,
'class' => AccompanyingPeriod\AccompanyingPeriodWork::class,
'name' => 'accompanying_period_work',
'base_path' => '/api/1.0/person/accompanying-course/work',
'controller' => \Chill\PersonBundle\Controller\AccompanyingCourseWorkApiController::class,
@@ -918,7 +916,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
*/
protected function prependDoctrineDQL(ContainerBuilder $container)
{
//add DQL function to ORM (default entity_manager)
// add DQL function to ORM (default entity_manager)
$container->prependExtensionConfig('doctrine', [
'orm' => [
@@ -1004,7 +1002,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
'property' => 'step',
],
'supports' => [
\Chill\PersonBundle\Entity\AccompanyingPeriod::class,
AccompanyingPeriod::class,
],
'initial_marking' => 'DRAFT',
'places' => [
@@ -1026,7 +1024,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
'mark_inactive_long' => [
'from' => [
AccompanyingPeriod::STEP_CONFIRMED,
AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_SHORT
AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_SHORT,
],
'to' => AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_LONG,
],
@@ -1035,7 +1033,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_LONG,
AccompanyingPeriod::STEP_CONFIRMED_INACTIVE_SHORT,
],
'to' => AccompanyingPeriod::STEP_CONFIRMED
'to' => AccompanyingPeriod::STEP_CONFIRMED,
],
'close' => [
'from' => [
@@ -1071,9 +1069,6 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
);
}
/**
* @param $config
*/
private function handleAccompanyingPeriodsFieldsParameters(ContainerBuilder $container, $config)
{
$container->setParameter('chill_person.accompanying_period_fields', $config);
@@ -1084,36 +1079,26 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
break;
default:
$container->setParameter('chill_person.accompanying_period_fields.' . $key, $value);
$container->setParameter('chill_person.accompanying_period_fields.'.$key, $value);
break;
}
}
}
/**
* @param $config
*/
private function handlePersonFieldsParameters(ContainerBuilder $container, $config)
{
if (array_key_exists('enabled', $config)) {
if (\array_key_exists('enabled', $config)) {
unset($config['enabled']);
}
$container->setParameter('chill_person.person_fields', $config);
foreach ($config as $key => $value) {
switch ($key) {
case 'accompanying_period':
$container->setParameter('chill_person.accompanying_period', $value);
break;
default:
$container->setParameter('chill_person.person_fields.' . $key, $value);
break;
}
match ($key) {
'accompanying_period' => $container->setParameter('chill_person.accompanying_period', $value),
default => $container->setParameter('chill_person.person_fields.'.$key, $value),
};
}
}
}

View File

@@ -14,8 +14,6 @@ namespace Chill\PersonBundle\DependencyInjection\CompilerPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use function in_array;
/**
* Remove services which add AccompanyingPeriod to timeline if
* accompanying_periods are set to `hidden`.
@@ -25,7 +23,7 @@ class AccompanyingPeriodTimelineCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
// remove services when accompanying period are hidden
if ($container->getParameter('chill_person.accompanying_period') !== 'hidden') {
if ('hidden' !== $container->getParameter('chill_person.accompanying_period')) {
return;
}
@@ -52,7 +50,7 @@ class AccompanyingPeriodTimelineCompilerPass implements CompilerPassInterface
$definition->removeMethodCall('addProvider');
if (false === in_array($arguments[1], $definitions, true)) {
if (false === \in_array($arguments[1], $definitions, true)) {
$definition->addMethodCall($method, $arguments);
}
}

View File

@@ -11,8 +11,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\DependencyInjection;
use DateInterval;
use Exception;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
@@ -23,9 +21,9 @@ use Symfony\Component\Config\Definition\ConfigurationInterface;
*/
class Configuration implements ConfigurationInterface
{
private $validationBirthdateNotAfterInfos = 'The period before today during which'
. ' any birthdate is not allowed. The birthdate is expressed as ISO8601 : '
. 'https://en.wikipedia.org/wiki/ISO_8601#Durations';
private string $validationBirthdateNotAfterInfos = 'The period before today during which'
.' any birthdate is not allowed. The birthdate is expressed as ISO8601 : '
.'https://en.wikipedia.org/wiki/ISO_8601#Durations';
public function getConfigTreeBuilder()
{
@@ -48,19 +46,19 @@ class Configuration implements ConfigurationInterface
->validate()
->ifTrue(static function ($period) {
try {
$interval = new DateInterval($period);
} catch (Exception $ex) {
$interval = new \DateInterval($period);
} catch (\Exception) {
return true;
}
return false;
})
->thenInvalid('Invalid period for birthdate validation : "%s" '
. 'The parameter should match duration as defined by ISO8601 : '
. 'https://en.wikipedia.org/wiki/ISO_8601#Durations')
.'The parameter should match duration as defined by ISO8601 : '
.'https://en.wikipedia.org/wiki/ISO_8601#Durations')
->end() // birthdate_not_after, parent = children of validation
->end() // children for 'validation', parent = validation
->end() //validation, parent = children of root
->end() // validation, parent = children of root
->end() // children of root, parent = root
->booleanNode('create_person_allowed')
->defaultTrue()
@@ -107,7 +105,7 @@ class Configuration implements ConfigurationInterface
->end()
->end()
->end()
->end() //children for 'person_fields', parent = array 'person_fields'
->end() // children for 'person_fields', parent = array 'person_fields'
->end() // person_fields, parent = children of root
->arrayNode('accompanying_periods_fields')
->canBeDisabled()
@@ -122,7 +120,7 @@ class Configuration implements ConfigurationInterface
->append($this->addFieldNode('anonymous'))
->append($this->addFieldNode('emergency'))
->append($this->addFieldNode('confidential'))
->end() //children for 'accompanying_person_fields', parent = array 'person_fields'
->end() // children for 'accompanying_person_fields', parent = array 'person_fields'
->end() // paccompanying_person_fields, parent = children of root
->booleanNode('allow_multiple_simultaneous_accompanying_periods')
->info('Can we have more than one simultaneous accompanying period in the same time. Default false.')
@@ -148,17 +146,10 @@ class Configuration implements ConfigurationInterface
$tree = new TreeBuilder($key, 'enum');
$node = $tree->getRootNode();
switch ($key) {
case 'accompanying_period':
$info = 'If the accompanying periods are shown';
break;
default:
$info = "If the field {$key} must be shown";
break;
}
$info = match ($key) {
'accompanying_period' => 'If the accompanying periods are shown',
default => "If the field {$key} must be shown",
};
$node
->values(['hidden', 'visible'])

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Doctrine\DQL;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
@@ -40,20 +39,14 @@ abstract class AddressPart extends FunctionNode
'country_id',
];
/**
* @var \Doctrine\ORM\Query\AST\Node
*/
private $date;
private \Doctrine\ORM\Query\AST\Node|string|null $date = null;
/**
* @var \Doctrine\ORM\Query\AST\Node
*/
private $part;
/**
* @var \Doctrine\ORM\Query\AST\Node
*/
private $pid;
private ?\Doctrine\ORM\Query\AST\PathExpression $pid = null;
/**
* return the part of the address.
@@ -79,13 +72,13 @@ abstract class AddressPart extends FunctionNode
public function parse(Parser $parser)
{
$a = $parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$a = $parser->match(\Doctrine\ORM\Query\TokenType::T_IDENTIFIER);
$parser->match(\Doctrine\ORM\Query\TokenType::T_OPEN_PARENTHESIS);
// person id
$this->pid = $parser->SingleValuedPathExpression();
$parser->match(Lexer::T_COMMA);
$parser->match(\Doctrine\ORM\Query\TokenType::T_COMMA);
// date
$this->date = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
$parser->match(\Doctrine\ORM\Query\TokenType::T_CLOSE_PARENTHESIS);
}
}

View File

@@ -11,6 +11,7 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Entity;
use Chill\CalendarBundle\Entity\Calendar;
use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Entity\Address;
@@ -37,37 +38,36 @@ use Chill\PersonBundle\Validator\Constraints\AccompanyingPeriod\ParticipationOve
use Chill\PersonBundle\Validator\Constraints\AccompanyingPeriod\ResourceDuplicateCheck;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\ReadableCollection;
use Doctrine\Common\Collections\Selectable;
use Doctrine\ORM\Mapping as ORM;
use Iterator;
use LogicException;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\GroupSequenceProviderInterface;
use UnexpectedValueException;
use function array_key_exists;
use const SORT_REGULAR;
/**
* AccompanyingPeriod Class.
*
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period")
*
* @DiscriminatorMap(typeProperty="type", mapping={
* "accompanying_period": AccompanyingPeriod::class
* })
*
* @Assert\GroupSequenceProvider
*
* @AccompanyingPeriodValidity(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED})
*
* @LocationValidity(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED})
*
* @ConfidentialCourseMustHaveReferrer(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED})
*/
class AccompanyingPeriod implements
@@ -77,21 +77,21 @@ class AccompanyingPeriod implements
TrackCreationInterface,
TrackUpdateInterface
{
public const INTENSITIES = [self::INTENSITY_OCCASIONAL, self::INTENSITY_REGULAR];
final public const INTENSITIES = [self::INTENSITY_OCCASIONAL, self::INTENSITY_REGULAR];
/**
* Mark an accompanying period as "occasional".
*
* used in INTENSITY
*/
public const INTENSITY_OCCASIONAL = 'occasional';
final public const INTENSITY_OCCASIONAL = 'occasional';
/**
* Mark an accompanying period as "regular".
*
* used in INTENSITY
*/
public const INTENSITY_REGULAR = 'regular';
final public const INTENSITY_REGULAR = 'regular';
/**
* Mark an accompanying period as "closed".
@@ -99,7 +99,7 @@ class AccompanyingPeriod implements
* This means that the accompanying period **is**
* closed by the creator
*/
public const STEP_CLOSED = 'CLOSED';
final public const STEP_CLOSED = 'CLOSED';
/**
* Mark an accompanying period as "confirmed".
@@ -107,25 +107,25 @@ class AccompanyingPeriod implements
* This means that the accompanying period **is**
* confirmed by the creator
*/
public const STEP_CONFIRMED = 'CONFIRMED';
final public const STEP_CONFIRMED = 'CONFIRMED';
/**
* Mark an accompanying period as confirmed, but inactive
* Mark an accompanying period as confirmed, but inactive.
*
* this means that the accompanying period **is**
* confirmed, but no activity (Activity, AccompanyingPeriod, ...)
* has been associated, or updated, within this accompanying period.
*/
public const STEP_CONFIRMED_INACTIVE_SHORT = 'CONFIRMED_INACTIVE_SHORT';
final public const STEP_CONFIRMED_INACTIVE_SHORT = 'CONFIRMED_INACTIVE_SHORT';
/**
* Mark an accompanying period as confirmed, but inactive
* Mark an accompanying period as confirmed, but inactive.
*
* this means that the accompanying period **is**
* confirmed, but no activity (Activity, AccompanyingPeriod, ...)
* has been associated, or updated, within this accompanying period.
*/
public const STEP_CONFIRMED_INACTIVE_LONG = 'CONFIRMED_INACTIVE_LONG';
final public const STEP_CONFIRMED_INACTIVE_LONG = 'CONFIRMED_INACTIVE_LONG';
/**
* Mark an accompanying period as "draft".
@@ -133,7 +133,7 @@ class AccompanyingPeriod implements
* This means that the accompanying period is not yet
* confirmed by the creator
*/
public const STEP_DRAFT = 'DRAFT';
final public const STEP_DRAFT = 'DRAFT';
/**
* @ORM\ManyToOne(
@@ -144,37 +144,43 @@ class AccompanyingPeriod implements
/**
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Location")
*
* @Groups({"read", "write"})
*
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CONFIRMED})
*/
private ?Location $administrativeLocation = null;
/**
* @var Collection&Selectable<int, Calendar>
*
* @ORM\OneToMany(targetEntity="Chill\CalendarBundle\Entity\Calendar", mappedBy="accompanyingPeriod")
*/
private Collection $calendars;
private Collection&Selectable $calendars;
/**
* @var DateTime
*
* @ORM\Column(type="date", nullable=true)
*
* @Groups({"read", "write", "docgen:read"})
*
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CLOSED})
*
* @Assert\GreaterThanOrEqual(
* propertyPath="openingDate",
* groups={AccompanyingPeriod::STEP_CLOSED},
* message="The closing date must be later than the date of creation"
* )
*/
private ?DateTime $closingDate = null;
private ?\DateTime $closingDate = null;
/**
* @var AccompanyingPeriod\ClosingMotive
*
* @ORM\ManyToOne(
* targetEntity="Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive")
*
* @ORM\JoinColumn(nullable=true)
*
* @Groups({"read", "write"})
*
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CLOSED})
*/
private ?ClosingMotive $closingMotive = null;
@@ -185,82 +191,102 @@ class AccompanyingPeriod implements
* cascade={"persist", "remove"},
* orphanRemoval=true
* )
*
* @ORM\OrderBy({"createdAt": "DESC", "id": "DESC"})
*
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_DRAFT})
*
* @var Collection<Comment>
*/
private Collection $comments;
/**
* @ORM\Column(type="boolean", options={"default": false})
*
* @Groups({"read", "write", "docgen:read"})
*/
private bool $confidential = false;
/**
* @ORM\Column(type="datetime", nullable=true, options={"default": NULL})
*
* @Groups({"docgen:read"})
*/
private ?DateTimeInterface $createdAt = null;
private ?\DateTimeInterface $createdAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=true)
*
* @Groups({"read", "docgen:read"})
*/
private ?User $createdBy = null;
/**
* @ORM\Column(type="boolean", options={"default": false})
*
* @Groups({"read", "write", "docgen:read"})
*/
private bool $emergency = false;
/**
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*
* @Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @var string
* @ORM\Column(type="string", nullable=true)
*
* @Groups({"read"})
*
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CONFIRMED})
*/
private $intensity = self::INTENSITY_OCCASIONAL;
private ?string $intensity = self::INTENSITY_OCCASIONAL;
/**
* @ORM\ManyToOne(
* targetEntity=UserJob::class
* )
*
* @Groups({"read", "write"})
*
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CONFIRMED})
*/
private ?UserJob $job = null;
/**
* @var Collection<AccompanyingPeriodLocationHistory>
*
* @ORM\OneToMany(targetEntity=AccompanyingPeriodLocationHistory::class,
* mappedBy="period", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private Collection $locationHistories;
/**
* @var DateTime
*
* @ORM\Column(type="date")
*
* @Groups({"read", "write", "docgen:read"})
*
* @Assert\LessThan(value="tomorrow", groups={AccompanyingPeriod::STEP_CONFIRMED})
*
* @Assert\LessThanOrEqual(propertyPath="closingDate", groups={AccompanyingPeriod::STEP_CONFIRMED})
*/
private ?DateTime $openingDate = null;
private ?\DateTime $openingDate = null;
/**
* @ORM\ManyToOne(targetEntity=Origin::class)
*
* @ORM\JoinColumn(nullable=true)
*
* @Groups({"read", "write"})
*
* @Assert\NotBlank(groups={AccompanyingPeriod::STEP_CONFIRMED})
*/
private ?Origin $origin = null;
@@ -269,8 +295,11 @@ class AccompanyingPeriod implements
* @ORM\OneToMany(targetEntity=AccompanyingPeriodParticipation::class,
* mappedBy="accompanyingPeriod", orphanRemoval=true,
* cascade={"persist", "refresh", "remove", "merge", "detach"})
*
* @Groups({"read", "docgen:read"})
*
* @ParticipationOverlap(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED})
*
* @var Collection<AccompanyingPeriodParticipation>
*/
private Collection $participations;
@@ -288,7 +317,9 @@ class AccompanyingPeriod implements
* targetEntity=Comment::class,
* cascade={"persist"},
* )
*
* @Groups({"read"})
*
* @ORM\JoinColumn(onDelete="SET NULL")
*/
private ?Comment $pinnedComment = null;
@@ -297,75 +328,97 @@ class AccompanyingPeriod implements
/**
* @ORM\Column(type="text")
*
* @Groups({"read", "write"})
*/
private string $remark = '';
/**
* @ORM\Column(type="boolean", options={"default": false})
*
* @Groups({"read", "write", "docgen:read"})
*/
private bool $requestorAnonymous = false;
/**
* @ORM\ManyToOne(targetEntity=Person::class, inversedBy="accompanyingPeriodRequested")
*
* @ORM\JoinColumn(nullable=true)
*/
private ?Person $requestorPerson = null;
/**
* @ORM\ManyToOne(targetEntity=ThirdParty::class)
*
* @ORM\JoinColumn(nullable=true)
*/
private ?ThirdParty $requestorThirdParty = null;
/**
* @var Collection<resource>
*
* @ORM\OneToMany(
* targetEntity="Chill\PersonBundle\Entity\AccompanyingPeriod\Resource",
* mappedBy="accompanyingPeriod",
* cascade={"persist", "remove"},
* orphanRemoval=true
* )
*
* @Groups({"read", "docgen:read"})
*
* @ResourceDuplicateCheck(groups={AccompanyingPeriod::STEP_DRAFT, AccompanyingPeriod::STEP_CONFIRMED, "Default", "default"})
*/
private Collection $resources;
/**
* @var Collection<Scope>
*
* @ORM\ManyToMany(
* targetEntity=Scope::class,
* cascade={}
* )
*
* @ORM\JoinTable(
* name="accompanying_periods_scopes",
* joinColumns={@ORM\JoinColumn(name="accompanying_period_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="scope_id", referencedColumnName="id")}
* )
*
* @Groups({"read", "docgen:read"})
*
* @Assert\Count(min=1, groups={AccompanyingPeriod::STEP_CONFIRMED}, minMessage="A course must be associated to at least one scope")
*/
private Collection $scopes;
/**
* @var Collection<SocialIssue>
*
* @ORM\ManyToMany(
* targetEntity=SocialIssue::class
* )
*
* @ORM\JoinTable(
* name="chill_person_accompanying_period_social_issues"
* )
*
* @Groups({"read", "docgen:read"})
*
* @Assert\Count(min=1, groups={AccompanyingPeriod::STEP_CONFIRMED}, minMessage="A course must contains at least one social issue")
*/
private Collection $socialIssues;
/**
* @ORM\Column(type="string", length=32, nullable=true)
*
* @Groups({"read"})
*
* @var AccompanyingPeriod::STEP_*
*/
private string $step = self::STEP_DRAFT;
private ?string $step = self::STEP_DRAFT;
/**
* @var Collection<AccompanyingPeriodStepHistory>
*
* @ORM\OneToMany(targetEntity=AccompanyingPeriodStepHistory::class,
* mappedBy="period", cascade={"persist", "remove"}, orphanRemoval=true)
*/
@@ -374,7 +427,7 @@ class AccompanyingPeriod implements
/**
* @ORM\Column(type="datetime", nullable=true, options={"default": NULL})
*/
private ?DateTimeInterface $updatedAt = null;
private ?\DateTimeInterface $updatedAt = null;
/**
* @ORM\ManyToOne(
@@ -385,7 +438,9 @@ class AccompanyingPeriod implements
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=true)
*
* @Groups({"read", "write", "docgen:read"})
*/
private ?User $user = null;
@@ -394,7 +449,7 @@ class AccompanyingPeriod implements
* @ORM\OneToMany(targetEntity=UserHistory::class, mappedBy="accompanyingPeriod", orphanRemoval=true,
* cascade={"persist", "remove"})
*
* @var Collection|UserHistory[]
* @var Collection<UserHistory>
*/
private Collection $userHistories;
@@ -408,10 +463,13 @@ class AccompanyingPeriod implements
private ?User $userPrevious = null;
/**
* @var Collection<AccompanyingPeriodWork>
*
* @ORM\OneToMany(
* targetEntity=AccompanyingPeriodWork::class,
* mappedBy="accompanyingPeriod"
* )
*
* @Assert\Valid(traverse=true)
*/
private Collection $works;
@@ -419,11 +477,9 @@ class AccompanyingPeriod implements
/**
* AccompanyingPeriod constructor.
*
* @param DateTime $dateOpening
*
* @uses AccompanyingPeriod::setClosingDate()
*/
public function __construct(?DateTime $dateOpening = null)
public function __construct(?\DateTime $dateOpening = null)
{
$this->calendars = new ArrayCollection(); // TODO we cannot add a dependency between AccompanyingPeriod and calendars
$this->participations = new ArrayCollection();
@@ -435,7 +491,7 @@ class AccompanyingPeriod implements
$this->userHistories = new ArrayCollection();
$this->locationHistories = new ArrayCollection();
$this->stepHistories = new ArrayCollection();
$this->setOpeningDate($dateOpening ?? new DateTime('now'));
$this->setOpeningDate($dateOpening ?? new \DateTime('now'));
}
/**
@@ -458,7 +514,7 @@ class AccompanyingPeriod implements
foreach ($participations as $p) {
$households[] = $p->getPerson()->getCurrentHousehold();
}
$households = array_unique($households, SORT_REGULAR);
$households = array_unique($households, \SORT_REGULAR);
$array = [];
@@ -488,7 +544,7 @@ class AccompanyingPeriod implements
public function addLocationHistory(AccompanyingPeriodLocationHistory $history): self
{
if ($this->getStep() === self::STEP_DRAFT) {
if (self::STEP_DRAFT === $this->getStep()) {
return $this;
}
@@ -499,9 +555,9 @@ class AccompanyingPeriod implements
// ensure continuity of histories
$criteria = new Criteria();
$criteria->orderBy(['startDate' => Criteria::ASC, 'id' => Criteria::ASC]);
$criteria->orderBy(['startDate' => \Doctrine\Common\Collections\Order::Ascending, 'id' => \Doctrine\Common\Collections\Order::Ascending]);
/** @var Iterator $locations */
/** @var \Iterator $locations */
$locations = $this->getLocationHistories()->matching($criteria)->getIterator();
$locations->rewind();
@@ -570,7 +626,7 @@ class AccompanyingPeriod implements
*/
public function canBeReOpened(Person $person): bool
{
if ($this->isOpen() === true) {
if (true === $this->isOpen()) {
return false;
}
@@ -590,15 +646,13 @@ class AccompanyingPeriod implements
*
* Search for the person's participation and set the end date at
* 'now'.
*
* @param mixed $person
*/
public function closeParticipationFor($person): ?AccompanyingPeriodParticipation
public function closeParticipationFor(mixed $person): ?AccompanyingPeriodParticipation
{
$participation = $this->getOpenParticipationContainsPerson($person);
if ($participation instanceof AccompanyingPeriodParticipation) {
$participation->setEndDate(new DateTime('now'));
$participation->setEndDate(new \DateTime('now'));
}
return $participation;
@@ -658,7 +712,7 @@ class AccompanyingPeriod implements
public function getCenter(): ?Center
{
if ($this->getPersons()->count() === 0) {
if (0 === $this->getPersons()->count()) {
return null;
}
@@ -672,7 +726,7 @@ class AccompanyingPeriod implements
foreach ($this->getPersons() as $person) {
if (
null !== $person->getCenter()
&& !array_key_exists(spl_object_hash($person->getCenter()), $centers)
&& !\array_key_exists(spl_object_hash($person->getCenter()), $centers)
) {
$centers[spl_object_hash($person->getCenter())] = $person->getCenter();
}
@@ -683,10 +737,8 @@ class AccompanyingPeriod implements
/**
* Get closingDate.
*
* @return DateTime
*/
public function getClosingDate(): ?DateTime
public function getClosingDate(): ?\DateTime
{
return $this->closingDate;
}
@@ -698,6 +750,7 @@ class AccompanyingPeriod implements
/**
* @Groups({"read"})
*
* @return ReadableCollection<(int|string), Comment>
*/
public function getComments(): ReadableCollection
@@ -712,7 +765,7 @@ class AccompanyingPeriod implements
;
}
public function getCreatedAt(): DateTimeInterface
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
@@ -732,17 +785,17 @@ class AccompanyingPeriod implements
public function getGroupSequence()
{
if ($this->getStep() === self::STEP_DRAFT) {
if (self::STEP_DRAFT === $this->getStep()) {
return [[self::STEP_DRAFT]];
}
if (str_starts_with($this->getStep(), 'CONFIRM')) {
if (str_starts_with((string) $this->getStep(), 'CONFIRM')) {
return [[self::STEP_DRAFT, self::STEP_CONFIRMED]];
}
if ($this->getStep() === self::STEP_CLOSED) {
if (self::STEP_CLOSED === $this->getStep()) {
return [[self::STEP_DRAFT, self::STEP_CONFIRMED, self::STEP_CLOSED]];
}
throw new LogicException('no validation group permitted with this step: ' . $this->getStep());
throw new \LogicException('no validation group permitted with this step: '.$this->getStep());
}
public function getId(): ?int
@@ -776,7 +829,7 @@ class AccompanyingPeriod implements
*
* @Groups({"read"})
*/
public function getLocation(?DateTimeImmutable $at = null): ?Address
public function getLocation(?\DateTimeImmutable $at = null): ?Address
{
if ($this->getPersonLocation() instanceof Person) {
return $this->getPersonLocation()->getCurrentPersonAddress();
@@ -797,6 +850,7 @@ class AccompanyingPeriod implements
* Get where the location is.
*
* @Groups({"read"})
*
* @return 'person'|'address'|'none'
*/
public function getLocationStatus(): string
@@ -812,12 +866,12 @@ class AccompanyingPeriod implements
return 'none';
}
public function getNextCalendarsForPerson(Person $person, $limit = 5): Collection
public function getNextCalendarsForPerson(Person $person, $limit = 5): ReadableCollection
{
$today = new DateTimeImmutable('today');
$today = new \DateTimeImmutable('today');
$criteria = Criteria::create()
->where(Criteria::expr()->gte('startDate', $today))
//->andWhere(Criteria::expr()->memberOf('persons', $person))
// ->andWhere(Criteria::expr()->memberOf('persons', $person))
->orderBy(['startDate' => 'DESC'])
->setMaxResults($limit * 2);
@@ -832,10 +886,8 @@ class AccompanyingPeriod implements
/**
* Get openingDate.
*
* @return DateTime
*/
public function getOpeningDate(): ?DateTime
public function getOpeningDate(): ?\DateTime
{
return $this->openingDate;
}
@@ -875,6 +927,7 @@ class AccompanyingPeriod implements
/**
* Get Participations Collection.
*
* @return Collection<AccompanyingPeriodParticipation>
*/
public function getParticipations(): Collection
@@ -884,6 +937,7 @@ class AccompanyingPeriod implements
/**
* Get the participation containing a person.
*
* @return ReadableCollection<(int|string), AccompanyingPeriodParticipation>
*/
public function getParticipationsContainsPerson(Person $person): ReadableCollection
@@ -932,7 +986,7 @@ class AccompanyingPeriod implements
/**
* @return Collection|SocialAction[] All the descendant social actions of all
* the descendants of the entity
* the descendants of the entity
*/
public function getRecursiveSocialActions(): Collection
{
@@ -973,10 +1027,9 @@ class AccompanyingPeriod implements
}
/**
* @return Person|ThirdParty
* @Groups({"read"})
*/
public function getRequestor()
public function getRequestor(): Person|ThirdParty|null
{
return $this->requestorPerson ?? $this->requestorThirdParty;
}
@@ -1108,11 +1161,11 @@ class AccompanyingPeriod implements
public function isOpen(): bool
{
if ($this->getOpeningDate() > new DateTimeImmutable('now')) {
if ($this->getOpeningDate() > new \DateTimeImmutable('now')) {
return false;
}
if ($this->getClosingDate() === null) {
if (null === $this->getClosingDate()) {
return true;
}
@@ -1213,7 +1266,7 @@ class AccompanyingPeriod implements
$this->setPersonLocation(null);
$locationHistory = new AccompanyingPeriodLocationHistory();
$locationHistory
->setStartDate(new DateTimeImmutable('now'))
->setStartDate(new \DateTimeImmutable('now'))
->setAddressLocation($addressLocation);
$this->addLocationHistory($locationHistory);
@@ -1235,11 +1288,9 @@ class AccompanyingPeriod implements
*
* For closing a Person file, you should use Person::setClosed instead.
*
* @param mixed $closingDate
*
* @return AccompanyingPeriod
*/
public function setClosingDate($closingDate)
public function setClosingDate(mixed $closingDate)
{
$this->closingDate = $closingDate;
@@ -1260,7 +1311,7 @@ class AccompanyingPeriod implements
return $this;
}
public function setCreatedAt(DateTimeInterface $datetime): self
public function setCreatedAt(\DateTimeInterface $datetime): self
{
$this->createdAt = $datetime;
@@ -1298,11 +1349,9 @@ class AccompanyingPeriod implements
/**
* Set openingDate.
*
* @param mixed $openingDate
*
* @return AccompanyingPeriod
*/
public function setOpeningDate($openingDate)
public function setOpeningDate(mixed $openingDate)
{
if ($this->openingDate !== $openingDate) {
$this->openingDate = $openingDate;
@@ -1332,7 +1381,7 @@ class AccompanyingPeriod implements
$this->setAddressLocation(null);
$locationHistory = new AccompanyingPeriodLocationHistory();
$locationHistory
->setStartDate(new DateTimeImmutable('now'))
->setStartDate(new \DateTimeImmutable('now'))
->setPersonLocation($person);
$this->addLocationHistory($locationHistory);
@@ -1370,7 +1419,9 @@ class AccompanyingPeriod implements
* instance of Person
*
* @param $requestor Person|ThirdParty
*
* @throw UnexpectedValueException if the requestor is not a Person or ThirdParty
*
* @Groups({"write"})
*/
public function setRequestor($requestor): self
@@ -1385,7 +1436,7 @@ class AccompanyingPeriod implements
$this->setRequestorPerson(null);
$this->setRequestorThirdParty(null);
} else {
throw new UnexpectedValueException('requestor is not an instance of Person or ThirdParty');
throw new \UnexpectedValueException('requestor is not an instance of Person or ThirdParty');
}
return $this;
@@ -1398,7 +1449,7 @@ class AccompanyingPeriod implements
return $this;
}
public function setStep(string $step): self
public function setStep(string $step, array $context = []): self
{
$previous = $this->step;
@@ -1411,15 +1462,15 @@ class AccompanyingPeriod implements
if (self::STEP_DRAFT !== $this->step && $previous !== $step) {
// we create a new history
$history = new AccompanyingPeriodStepHistory();
$history->setStep($this->step)->setStartDate(new DateTimeImmutable('now'));
$history->setStep($this->step)->setStartDate(new \DateTimeImmutable('now'));
$this->addStepHistory($history);
$this->addStepHistory($history, $context);
}
return $this;
}
public function setUpdatedAt(DateTimeInterface $datetime): self
public function setUpdatedAt(\DateTimeInterface $datetime): self
{
$this->updatedAt = $datetime;
@@ -1442,7 +1493,7 @@ class AccompanyingPeriod implements
foreach ($this->userHistories as $history) {
if (null === $history->getEndDate()) {
$history->setEndDate(new DateTimeImmutable('now'));
$history->setEndDate(new \DateTimeImmutable('now'));
}
}
@@ -1456,11 +1507,14 @@ class AccompanyingPeriod implements
return $this;
}
private function addStepHistory(AccompanyingPeriodStepHistory $stepHistory): self
private function addStepHistory(AccompanyingPeriodStepHistory $stepHistory, array $context = []): self
{
if (!$this->stepHistories->contains($stepHistory)) {
$this->stepHistories[] = $stepHistory;
$stepHistory->setPeriod($this);
if (($context['closing_motive'] ?? null) instanceof ClosingMotive) {
$stepHistory->setClosingMotive($context['closing_motive']);
}
$this->ensureStepContinuity();
}
@@ -1472,7 +1526,7 @@ class AccompanyingPeriod implements
// first location history
$locationHistory = new AccompanyingPeriodLocationHistory();
$locationHistory
->setStartDate(new DateTimeImmutable('now'))
->setStartDate(new \DateTimeImmutable('now'))
->setPersonLocation($this->getPersonLocation())
->setAddressLocation($this->getAddressLocation());
$this->addLocationHistory($locationHistory);
@@ -1482,9 +1536,9 @@ class AccompanyingPeriod implements
{
// ensure continuity of histories
$criteria = new Criteria();
$criteria->orderBy(['startDate' => Criteria::ASC, 'id' => Criteria::ASC]);
$criteria->orderBy(['startDate' => \Doctrine\Common\Collections\Order::Ascending, 'id' => \Doctrine\Common\Collections\Order::Ascending]);
/** @var Iterator $steps */
/** @var \Iterator $steps */
$steps = $this->getStepHistories()->matching($criteria)->getIterator();
$steps->rewind();
@@ -1499,7 +1553,7 @@ class AccompanyingPeriod implements
if ($this->getOpeningDate()->format('Y-m-d') !== $current->getStartDate()->format('Y-m-d')
&& ($this->getOpeningDate() <= $current->getEndDate() || null === $current->getEndDate())) {
$current->setStartDate(DateTimeImmutable::createFromMutable($this->getOpeningDate()));
$current->setStartDate(\DateTimeImmutable::createFromMutable($this->getOpeningDate()));
}
// then we set all the end date to the start date of the next one

View File

@@ -16,7 +16,7 @@ use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Doctrine\ORM\Mapping as ORM;
/**
* Informations about AccompanyingPeriod
* Informations about AccompanyingPeriod.
*
* This entity allow access to some basic information about the AccompanyingPeriod. It is
* populated from a SQL view, dynamically build from various sources.
@@ -26,6 +26,7 @@ use Doctrine\ORM\Mapping as ORM;
* - get the user involved with an accompanying period
*
* @ORM\Entity()
*
* @ORM\Table(name="view_chill_person_accompanying_period_info")
*/
class AccompanyingPeriodInfo
@@ -33,44 +34,53 @@ class AccompanyingPeriodInfo
public function __construct(
/**
* @var AccompanyingPeriod
*
* @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class)
*/
public readonly AccompanyingPeriod $accompanyingPeriod,
/**
* @var string
*
* @ORM\Column(type="text")
*
* @ORM\Id
*/
public readonly string $relatedEntity,
/**
* @var int
*
* @ORM\Column(type="integer")
*
* @ORM\Id
*/
public readonly int $relatedEntityId,
/**
* @var User
*
* @ORM\ManyToOne(targetEntity=User::class)
*/
public readonly ?User $user,
public readonly ?User $user,
/**
* @var \DateTimeImmutable
*
* @ORM\Column(type="datetime_immutable")
*/
public readonly \DateTimeImmutable $infoDate,
/**
* @var array
*
* @ORM\Column(type="json")
*/
public readonly array $metadata,
/**
* @var string
*
* @ORM\Column(type="text")
*/
public readonly string $discriminator,

View File

@@ -16,11 +16,11 @@ use Chill\MainBundle\Doctrine\Model\TrackCreationTrait;
use Chill\MainBundle\Entity\Address;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*
* @ORM\Table("chill_person_accompanying_period_location_history")
*/
class AccompanyingPeriodLocationHistory implements TrackCreationInterface
@@ -35,11 +35,13 @@ class AccompanyingPeriodLocationHistory implements TrackCreationInterface
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*/
private ?int $id = null;
@@ -57,14 +59,14 @@ class AccompanyingPeriodLocationHistory implements TrackCreationInterface
/**
* @ORM\Column(type="date_immutable")
*/
private ?DateTimeImmutable $startDate = null;
private ?\DateTimeImmutable $startDate = null;
public function getAddressLocation(): ?Address
{
return $this->addressLocation;
}
public function getEndDate(): ?DateTimeImmutable
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -84,7 +86,7 @@ class AccompanyingPeriodLocationHistory implements TrackCreationInterface
return $this->personLocation;
}
public function getStartDate(): ?DateTimeImmutable
public function getStartDate(): ?\DateTimeImmutable
{
return $this->startDate;
}
@@ -96,7 +98,7 @@ class AccompanyingPeriodLocationHistory implements TrackCreationInterface
return $this;
}
public function setEndDate(?DateTimeImmutable $endDate): AccompanyingPeriodLocationHistory
public function setEndDate(?\DateTimeImmutable $endDate): AccompanyingPeriodLocationHistory
{
$this->endDate = $endDate;
@@ -120,7 +122,7 @@ class AccompanyingPeriodLocationHistory implements TrackCreationInterface
return $this;
}
public function setStartDate(?DateTimeImmutable $startDate): AccompanyingPeriodLocationHistory
public function setStartDate(?\DateTimeImmutable $startDate): AccompanyingPeriodLocationHistory
{
$this->startDate = $startDate;

View File

@@ -17,11 +17,11 @@ use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateTrait;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*
* @ORM\Table("chill_person_accompanying_period_step_history")
*/
class AccompanyingPeriodStepHistory implements TrackCreationInterface, TrackUpdateInterface
@@ -33,11 +33,13 @@ class AccompanyingPeriodStepHistory implements TrackCreationInterface, TrackUpda
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*/
private ?int $id = null;
@@ -50,14 +52,21 @@ class AccompanyingPeriodStepHistory implements TrackCreationInterface, TrackUpda
/**
* @ORM\Column(type="date_immutable")
*/
private ?DateTimeImmutable $startDate = null;
private ?\DateTimeImmutable $startDate = null;
/**
* @ORM\Column(type="text", nullable=false)
*/
private string $step;
public function getEndDate(): ?DateTimeImmutable
/**
* @ORM\ManyToOne(targetEntity=ClosingMotive::class)
*
* @ORM\JoinColumn(nullable=true)
*/
private ?ClosingMotive $closingMotive = null;
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -72,7 +81,7 @@ class AccompanyingPeriodStepHistory implements TrackCreationInterface, TrackUpda
return $this->period;
}
public function getStartDate(): ?DateTimeImmutable
public function getStartDate(): ?\DateTimeImmutable
{
return $this->startDate;
}
@@ -82,7 +91,7 @@ class AccompanyingPeriodStepHistory implements TrackCreationInterface, TrackUpda
return $this->step;
}
public function setEndDate(?DateTimeImmutable $endDate): self
public function setEndDate(?\DateTimeImmutable $endDate): self
{
$this->endDate = $endDate;
@@ -99,7 +108,7 @@ class AccompanyingPeriodStepHistory implements TrackCreationInterface, TrackUpda
return $this;
}
public function setStartDate(?DateTimeImmutable $startDate): self
public function setStartDate(?\DateTimeImmutable $startDate): self
{
$this->startDate = $startDate;
@@ -112,4 +121,16 @@ class AccompanyingPeriodStepHistory implements TrackCreationInterface, TrackUpda
return $this;
}
public function getClosingMotive(): ?ClosingMotive
{
return $this->closingMotive;
}
public function setClosingMotive(?ClosingMotive $closingMotive): self
{
$this->closingMotive = $closingMotive;
return $this;
}
}

View File

@@ -22,18 +22,18 @@ use Chill\PersonBundle\Entity\SocialWork\Result;
use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Chill\PersonBundle\Entity\SocialWork\SocialIssue;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ReadableCollection;
use Doctrine\ORM\Mapping as ORM;
use LogicException;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period_work")
*
* @Serializer\DiscriminatorMap(
* typeProperty="type",
* mapping={
@@ -45,7 +45,9 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
{
/**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class)
*
* @Serializer\Groups({"read", "read:accompanyingPeriodWork:light"})
*
* @Serializer\Context(normalizationContext={"groups": {"read"}}, groups={"read:accompanyingPeriodWork:light"})
*/
private ?AccompanyingPeriod $accompanyingPeriod = null;
@@ -57,8 +59,11 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
* cascade={"remove", "persist"},
* orphanRemoval=true
* )
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @ORM\OrderBy({"startDate": "DESC", "id": "DESC"})
*
* @var Collection<AccompanyingPeriodWorkEvaluation>
*
* @internal /!\ the serialization for write evaluations is handled in `AccompanyingPeriodWorkDenormalizer`
@@ -67,47 +72,57 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
/**
* @ORM\Column(type="datetime_immutable")
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
*/
private ?DateTimeImmutable $createdAt = null;
private ?\DateTimeImmutable $createdAt = null;
/**
* @ORM\Column(type="boolean")
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
*/
private bool $createdAutomatically = false;
/**
* @ORM\Column(type="text")
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
*/
private string $createdAutomaticallyReason = '';
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=false)
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
*/
private ?User $createdBy = null;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"accompanying_period_work:create"})
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
*
* @Assert\GreaterThanOrEqual(propertyPath="startDate",
* message="accompanying_course_work.The endDate should be greater or equal than the start date"
* )
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @var Collection<AccompanyingPeriodWorkGoal>
*
* @ORM\OneToMany(
* targetEntity=AccompanyingPeriodWorkGoal::class,
* mappedBy="accompanyingPeriodWork",
* cascade={"persist"},
* orphanRemoval=true
* )
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"accompanying_period_work:edit"})
*/
@@ -115,6 +130,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
/**
* @ORM\ManyToOne(targetEntity=ThirdParty::class)
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"accompanying_period_work:edit"})
*
@@ -124,21 +140,29 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light", "read:evaluation:include-work"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="text")
*
* @Serializer\Groups({"read", "accompanying_period_work:edit", "docgen:read"})
*/
private string $note = '';
/**
* @var Collection<Person>
*
* @ORM\ManyToMany(targetEntity=Person::class)
*
* @ORM\JoinTable(name="chill_person_accompanying_period_work_person")
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"accompanying_period_work:create"})
@@ -147,22 +171,25 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
/**
* @ORM\Embedded(class="Chill\MainBundle\Entity\Embeddable\PrivateCommentEmbeddable", columnPrefix="privateComment_")
*
* @Serializer\Groups({"read", "accompanying_period_work:edit"})
*/
private PrivateCommentEmbeddable $privateComment;
/**
* @ORM\ManyToMany(targetEntity=User::class)
* @ORM\JoinTable(name="chill_person_accompanying_period_work_referrer")
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"accompanying_period_work:create"})
* @var Collection<int, AccompanyingPeriodWorkReferrerHistory>
*
* @ORM\OneToMany(targetEntity=AccompanyingPeriodWorkReferrerHistory::class, cascade={"persist", "remove"}, mappedBy="accompanyingPeriodWork", orphanRemoval=true)
*/
private Collection $referrers;
private Collection $referrersHistory;
/**
* @var Collection<Result>
*
* @ORM\ManyToMany(targetEntity=Result::class, inversedBy="accompanyingPeriodWorks")
*
* @ORM\JoinTable(name="chill_person_accompanying_period_work_result")
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"accompanying_period_work:edit"})
*/
@@ -170,25 +197,32 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
/**
* @ORM\ManyToOne(targetEntity=SocialAction::class)
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
* @Serializer\Groups({"accompanying_period_work:create"})
*
* @Serializer\Context(normalizationContext={"groups": {"read"}}, groups={"read:accompanyingPeriodWork:light"})
*/
private ?SocialAction $socialAction = null;
/**
* @ORM\Column(type="date_immutable")
*
* @Serializer\Groups({"accompanying_period_work:create"})
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
*/
private ?DateTimeImmutable $startDate = null;
private ?\DateTimeImmutable $startDate = null;
/**
* @var Collection<ThirdParty>
*
* @ORM\ManyToMany(targetEntity=ThirdParty::class)
*
* @ORM\JoinTable(name="chill_person_accompanying_period_work_third_party")
*
* In schema : intervenants
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"accompanying_period_work:edit"})
*/
@@ -196,17 +230,29 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
/**
* @ORM\Column(type="datetime_immutable")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?DateTimeImmutable $updatedAt = null;
private ?\DateTimeImmutable $updatedAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=false)
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?User $updatedBy = null;
/**
* @ORM\Column(type="integer", nullable=false, options={"default": 1})
*
* @Serializer\Groups({"read", "accompanying_period_work:edit"})
*
* @ORM\Version
*/
private int $version = 1;
public function __construct()
{
$this->goals = new ArrayCollection();
@@ -215,7 +261,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
$this->thirdParties = new ArrayCollection();
$this->persons = new ArrayCollection();
$this->accompanyingPeriodWorkEvaluations = new ArrayCollection();
$this->referrers = new ArrayCollection();
$this->referrersHistory = new ArrayCollection();
}
public function addAccompanyingPeriodWorkEvaluation(AccompanyingPeriodWorkEvaluation $evaluation): self
@@ -249,8 +295,9 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
public function addReferrer(User $referrer): self
{
if (!$this->referrers->contains($referrer)) {
$this->referrers[] = $referrer;
if (!$this->getReferrers()->contains($referrer)) {
$this->referrersHistory[] =
new AccompanyingPeriodWorkReferrerHistory($this, $referrer, new \DateTimeImmutable('today'));
}
return $this;
@@ -287,7 +334,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return $this->accompanyingPeriodWorkEvaluations;
}
public function getCreatedAt(): ?DateTimeImmutable
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
@@ -307,7 +354,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return $this->createdBy;
}
public function getEndDate(): ?DateTimeInterface
public function getEndDate(): ?\DateTimeInterface
{
return $this->endDate;
}
@@ -346,15 +393,30 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
}
/**
* @return Collection|User[]
* @return ReadableCollection<int, User>
*
* @Serializer\Groups({"read", "docgen:read", "read:accompanyingPeriodWork:light"})
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"accompanying_period_work:create"})
*/
public function getReferrers(): Collection
public function getReferrers(): ReadableCollection
{
return $this->referrers;
$users = $this->referrersHistory
->filter(fn (AccompanyingPeriodWorkReferrerHistory $h) => null === $h->getEndDate())
->map(fn (AccompanyingPeriodWorkReferrerHistory $h) => $h->getUser())
->getValues()
;
return new ArrayCollection(array_values($users));
}
public function getReferrersHistory(): Collection
{
return $this->referrersHistory;
}
/**
* @return Collection|Result[]
* @return Collection<int, Result>
*/
public function getResults(): Collection
{
@@ -371,7 +433,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return new ArrayCollection([$this->getSocialAction()->getIssue()]);
}
public function getStartDate(): ?DateTimeInterface
public function getStartDate(): ?\DateTimeInterface
{
return $this->startDate;
}
@@ -389,7 +451,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return $this->getThirdParties();
}
public function getUpdatedAt(): ?DateTimeImmutable
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
@@ -399,6 +461,18 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return $this->updatedBy;
}
public function getVersion(): int
{
return $this->version;
}
public function setVersion(int $version): self
{
$this->version = $version;
return $this;
}
public function removeAccompanyingPeriodWorkEvaluation(AccompanyingPeriodWorkEvaluation $evaluation): self
{
$this->accompanyingPeriodWorkEvaluations
@@ -429,7 +503,16 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
public function removeReferrer(User $referrer): self
{
$this->referrers->removeElement($referrer);
foreach ($this->referrersHistory as $history) {
if ($history->isOpen() && $referrer === $history->getUser()) {
$history->setEndDate(new \DateTimeImmutable('today'));
if ($history->isDateRangeEmpty()) {
$history->removeAccompanyingPeriodWork();
$this->referrersHistory->removeElement($history);
}
}
}
return $this;
}
@@ -465,7 +548,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
$this->accompanyingPeriod instanceof AccompanyingPeriod
&& $accompanyingPeriod !== $this->accompanyingPeriod
) {
throw new LogicException('A work cannot change accompanyingPeriod');
throw new \LogicException('A work cannot change accompanyingPeriod');
}
$this->accompanyingPeriod = $accompanyingPeriod;
@@ -473,7 +556,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return $this;
}
public function setCreatedAt(DateTimeInterface $createdAt): self
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
@@ -501,7 +584,7 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return $this;
}
public function setEndDate(?DateTimeInterface $endDate = null): self
public function setEndDate(?\DateTimeInterface $endDate = null): self
{
$this->endDate = $endDate;
@@ -536,14 +619,14 @@ class AccompanyingPeriodWork implements AccompanyingPeriodLinkedWithSocialIssues
return $this;
}
public function setStartDate(DateTimeInterface $startDate): self
public function setStartDate(\DateTimeInterface $startDate): self
{
$this->startDate = $startDate;
return $this;
}
public function setUpdatedAt(DateTimeInterface $datetime): TrackUpdateInterface
public function setUpdatedAt(\DateTimeInterface $datetime): TrackUpdateInterface
{
$this->updatedAt = $datetime;

View File

@@ -16,18 +16,16 @@ use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Entity\SocialWork\Evaluation;
use DateInterval;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use LogicException;
use RuntimeException;
use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Entity
*
* @ORM\Table("chill_person_accompanying_period_work_evaluation")
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "accompanying_period_work_evaluation": AccompanyingPeriodWorkEvaluation::class,
* })
@@ -39,13 +37,16 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
* targetEntity=AccompanyingPeriodWork::class,
* inversedBy="accompanyingPeriodWorkEvaluations"
* )
*
* @Serializer\Groups({"read:evaluation:include-work"})
*
* @Serializer\Context(normalizationContext={"groups": {"read:accompanyingPeriodWork:light"}}, groups={"read:evaluation:include-work"})
*/
private ?AccompanyingPeriodWork $accompanyingPeriodWork = null;
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
@@ -54,14 +55,16 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?DateTimeImmutable $createdAt = null;
private ?\DateTimeImmutable $createdAt = null;
/**
* @ORM\ManyToOne(
* targetEntity=User::class
* )
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?User $createdBy = null;
@@ -77,24 +80,29 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
* cascade={"remove", "persist"},
* orphanRemoval=true
* )
*
* @ORM\OrderBy({"createdAt": "DESC", "id": "DESC"})
*
* @Serializer\Groups({"read"})
*
* @var Collection<AccompanyingPeriodWorkEvaluationDocument>
*/
private Collection $documents;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\ManyToOne(
* targetEntity=Evaluation::class
* )
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*/
@@ -102,8 +110,11 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
@@ -118,51 +129,55 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
* @Serializer\Groups({"read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*
* @var mixed
*/
private $key;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*/
private ?DateTimeImmutable $maxDate = null;
private ?\DateTimeImmutable $maxDate = null;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*/
private ?DateTimeImmutable $startDate = null;
private ?\DateTimeImmutable $startDate = null;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?DateTimeImmutable $updatedAt = null;
private ?\DateTimeImmutable $updatedAt = null;
/**
* @ORM\ManyToOne(
* targetEntity=User::class
* )
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?User $updatedBy = null;
/**
* @ORM\Column(type="dateinterval", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*/
private ?DateInterval $warningInterval = null;
private ?\DateInterval $warningInterval = null;
/**
* @ORM\Column(type="integer", nullable=true)
*
* @Serializer\Groups({"read", "docgen:read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
@@ -194,7 +209,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
return $this->comment;
}
public function getCreatedAt(): ?DateTimeImmutable
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
@@ -212,7 +227,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
return $this->documents;
}
public function getEndDate(): ?DateTimeImmutable
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -229,25 +244,23 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
/**
* Arbitrary data, used for client.
*
* @return mixed
*/
public function getKey()
{
return $this->key;
}
public function getMaxDate(): ?DateTimeImmutable
public function getMaxDate(): ?\DateTimeImmutable
{
return $this->maxDate;
}
public function getStartDate(): ?DateTimeImmutable
public function getStartDate(): ?\DateTimeImmutable
{
return $this->startDate;
}
public function getUpdatedAt(): ?DateTimeImmutable
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
@@ -260,7 +273,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
/**
* @Serializer\Groups({"docgen:read"})
*/
public function getWarningDate(): ?DateTimeImmutable
public function getWarningDate(): ?\DateTimeImmutable
{
if (null === $this->getEndDate() || null === $this->getWarningInterval()) {
return null;
@@ -269,7 +282,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
return $this->getEndDate()->sub($this->getWarningInterval());
}
public function getWarningInterval(): ?DateInterval
public function getWarningInterval(): ?\DateInterval
{
return $this->warningInterval;
}
@@ -294,8 +307,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
&& $this->accompanyingPeriodWork instanceof AccompanyingPeriodWork
&& $this->accompanyingPeriodWork->getId() !== $accompanyingPeriodWork->getId()
) {
throw new RuntimeException('Changing the ' .
'accompanyingPeriodWork is not allowed');
throw new \RuntimeException('Changing the accompanyingPeriodWork is not allowed');
}
$this->accompanyingPeriodWork = $accompanyingPeriodWork;
@@ -311,11 +323,9 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
}
/**
* @param DateTimeImmutable|null $createdAt
*
* @return AccompanyingPeriodWorkEvaluation
* @param \DateTimeImmutable|null $createdAt
*/
public function setCreatedAt(DateTimeInterface $createdAt): self
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
@@ -329,7 +339,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
return $this;
}
public function setEndDate(?DateTimeImmutable $endDate): AccompanyingPeriodWorkEvaluation
public function setEndDate(?\DateTimeImmutable $endDate): AccompanyingPeriodWorkEvaluation
{
$this->endDate = $endDate;
@@ -354,7 +364,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
) {
$cl = AccompanyingPeriodWorkEvaluation::class;
throw new LogicException("once set, an {$cl} cannot
throw new \LogicException("once set, an {$cl} cannot
change or remove the linked Evaluation::class");
}
@@ -365,26 +375,22 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
/**
* Arbitrary data, used for client.
*
* @param mixed $key
*
* @return AccompanyingPeriodWorkEvaluation
*/
public function setKey($key): self
public function setKey(mixed $key): self
{
$this->key = $key;
return $this;
}
public function setMaxDate(?DateTimeImmutable $maxDate): AccompanyingPeriodWorkEvaluation
public function setMaxDate(?\DateTimeImmutable $maxDate): AccompanyingPeriodWorkEvaluation
{
$this->maxDate = $maxDate;
return $this;
}
public function setStartDate(?DateTimeImmutable $startDate): AccompanyingPeriodWorkEvaluation
public function setStartDate(?\DateTimeImmutable $startDate): AccompanyingPeriodWorkEvaluation
{
$this->startDate = $startDate;
@@ -392,11 +398,9 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
}
/**
* @param DateTimeImmutable|null $updatedAt
*
* @return AccompanyingPeriodWorkEvaluation
* @param \DateTimeImmutable|null $updatedAt
*/
public function setUpdatedAt(DateTimeInterface $updatedAt): self
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
@@ -410,7 +414,7 @@ class AccompanyingPeriodWorkEvaluation implements TrackCreationInterface, TrackU
return $this;
}
public function setWarningInterval(?DateInterval $warningInterval): AccompanyingPeriodWorkEvaluation
public function setWarningInterval(?\DateInterval $warningInterval): AccompanyingPeriodWorkEvaluation
{
$this->warningInterval = $warningInterval;

View File

@@ -16,13 +16,14 @@ use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\MainBundle\Doctrine\Model\TrackCreationTrait;
use Chill\MainBundle\Doctrine\Model\TrackUpdateTrait;
use Doctrine\ORM\Mapping as ORM;
use RuntimeException;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
*
* @ORM\Table("chill_person_accompanying_period_work_evaluation_document")
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "accompanying_period_work_evaluation_document": AccompanyingPeriodWorkEvaluationDocument::class
* })
@@ -43,11 +44,15 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @internal the default name exceeds 64 characters, we must set manually:
*
* @ORM\SequenceGenerator(sequenceName="chill_person_social_work_eval_doc_id_seq", allocationSize=1, initialValue=1000)
*
* @Serializer\Groups({"read"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*/
@@ -63,8 +68,6 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
* @Serializer\Groups({"read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*
* @var mixed
*/
private $key;
@@ -72,9 +75,11 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
* @ORM\ManyToOne(
* targetEntity=StoredObject::class,
* )
*
* @Serializer\Groups({"read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*
* @Assert\Valid
*/
private ?StoredObject $storedObject = null;
@@ -83,6 +88,7 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
* @ORM\ManyToOne(
* targetEntity=DocGeneratorTemplate::class
* )
*
* @Serializer\Groups({"read"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
*/
@@ -90,6 +96,7 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Serializer\Groups({"read"})
* @Serializer\Groups({"write"})
* @Serializer\Groups({"accompanying_period_work_evaluation:create"})
@@ -106,9 +113,6 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
return $this->id;
}
/**
* @return mixed
*/
public function getKey()
{
return $this->key;
@@ -138,7 +142,7 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
&& $accompanyingPeriodWorkEvaluation instanceof AccompanyingPeriodWorkEvaluation
) {
if ($this->accompanyingPeriodWorkEvaluation !== $accompanyingPeriodWorkEvaluation) {
throw new RuntimeException('It is not allowed to change the evaluation for a document');
throw new \RuntimeException('It is not allowed to change the evaluation for a document');
}
}
$this->accompanyingPeriodWorkEvaluation = $accompanyingPeriodWorkEvaluation;
@@ -147,11 +151,9 @@ class AccompanyingPeriodWorkEvaluationDocument implements \Chill\MainBundle\Doct
}
/**
* @param mixed $key
*
* @return AccompanyingPeriodWorkEvaluationDocument
*/
public function setKey($key)
public function setKey(mixed $key)
{
$this->key = $key;

View File

@@ -16,12 +16,13 @@ use Chill\PersonBundle\Entity\SocialWork\Result;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use LogicException;
use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period_work_goal")
*
* @Serializer\DiscriminatorMap(
* typeProperty="type",
* mapping={
@@ -34,10 +35,11 @@ class AccompanyingPeriodWorkGoal
/**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriodWork::class, inversedBy="goals")
*/
private $accompanyingPeriodWork;
private ?AccompanyingPeriodWork $accompanyingPeriodWork = null;
/**
* @ORM\ManyToOne(targetEntity=Goal::class)
*
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read", "docgen:read"})
*/
@@ -45,22 +47,30 @@ class AccompanyingPeriodWorkGoal
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="text")
*
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read"})
*/
private ?string $note = null;
private string $note = '';
/**
* @var Collection<Result>
*
* @ORM\ManyToMany(targetEntity=Result::class, inversedBy="accompanyingPeriodWorkGoals")
*
* @ORM\JoinTable(name="chill_person_accompanying_period_work_goal_result")
*
* @Serializer\Groups({"accompanying_period_work:edit"})
* @Serializer\Groups({"read", "docgen:read"})
*/
@@ -122,7 +132,7 @@ class AccompanyingPeriodWorkGoal
&& $accompanyingPeriodWork !== $this->accompanyingPeriodWork
&& null !== $accompanyingPeriodWork
) {
throw new LogicException('Change accompanying period work is not allowed');
throw new \LogicException('Change accompanying period work is not allowed');
}
$this->accompanyingPeriodWork = $accompanyingPeriodWork;

View File

@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackCreationTrait;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateTrait;
use Chill\MainBundle\Entity\User;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period_work_referrer")
*/
class AccompanyingPeriodWorkReferrerHistory implements TrackCreationInterface, TrackUpdateInterface
{
use TrackCreationTrait;
use TrackUpdateTrait;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*/
private ?int $id = null;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*/
private ?\DateTimeImmutable $endDate = null;
public function __construct(
/**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriodWork::class, inversedBy="referrersHistory")
*/
private ?AccompanyingPeriodWork $accompanyingPeriodWork,
/**
* @var User
*
* @ORM\ManyToOne(targetEntity=User::class)
*/
private User $user,
/**
* @var \DateTimeImmutable
*
* @ORM\Column(type="date_immutable", nullable=false)
*/
private \DateTimeImmutable $startDate
) {
}
public function getId(): ?int
{
return $this->id;
}
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
public function setEndDate(?\DateTimeImmutable $endDate): AccompanyingPeriodWorkReferrerHistory
{
$this->endDate = $endDate;
return $this;
}
public function getAccompanyingPeriodWork(): AccompanyingPeriodWork
{
return $this->accompanyingPeriodWork;
}
public function getUser(): User
{
return $this->user;
}
public function getStartDate(): \DateTimeImmutable
{
return $this->startDate;
}
/**
* to be used when the history is removed (when startDate = endDate).
*/
public function removeAccompanyingPeriodWork(): self
{
$this->accompanyingPeriodWork = null;
return $this;
}
/**
* @return bool true if the endDate is null
*/
public function isOpen(): bool
{
return null === $this->getEndDate();
}
/**
* return true if the date range is empty (start date and end date are equal).
*
* @return bool true if the start date and end date are equal
*/
public function isDateRangeEmpty(): bool
{
return $this->getStartDate()->format('Y-m-d') === $this->getEndDate()?->format('Y-m-d');
}
}

View File

@@ -20,6 +20,7 @@ use Symfony\Component\Serializer\Annotation as Serializer;
* ClosingMotive give an explanation why we closed the Accompanying period.
*
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period_closingmotive")
*/
class ClosingMotive
@@ -32,6 +33,8 @@ class ClosingMotive
/**
* Child Accompanying periods.
*
* @var Collection<ClosingMotive>
*
* @ORM\OneToMany(
* targetEntity="Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive",
* mappedBy="parent")
@@ -39,18 +42,21 @@ class ClosingMotive
private Collection $children;
/**
* @var int
*
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*
* @Serializer\Groups({"docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="json")
*
* @Serializer\Groups({"docgen:read"})
*
* @Serializer\Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $name = [];
@@ -61,14 +67,17 @@ class ClosingMotive
private float $ordering = 0.0;
/**
* @var self
*
* @ORM\ManyToOne(
* targetEntity="Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive",
* inversedBy="children")
*/
private ?ClosingMotive $parent = null;
/**
* @ORM\Column(type="boolean", nullable=false, options={"default": false})
*/
private bool $isCanceledAccompanyingPeriod = false;
/**
* ClosingMotive constructor.
*/
@@ -84,7 +93,7 @@ class ClosingMotive
}
$this->children->add($child);
$child->setParent($this);
$child->setParent($this)->setIsCanceledAccompanyingPeriod($this->getIsCanceledAccompanyingPeriod());
return $this;
}
@@ -127,6 +136,11 @@ class ClosingMotive
return $this->parent;
}
public function getIsCanceledAccompanyingPeriod(): bool
{
return $this->isCanceledAccompanyingPeriod;
}
public function hasParent(): bool
{
return null !== $this->parent;
@@ -144,7 +158,7 @@ class ClosingMotive
public function isLeaf(): bool
{
return $this->children->count() === 0;
return 0 === $this->children->count();
}
public function isParent(): bool
@@ -152,6 +166,11 @@ class ClosingMotive
return $this->children->count() > 0;
}
public function isCanceledAccompanyingPeriod(): bool
{
return $this->isCanceledAccompanyingPeriod;
}
public function removeChildren(ClosingMotive $child): ClosingMotive
{
if ($this->children->removeElement($child)) {
@@ -213,7 +232,18 @@ class ClosingMotive
$this->parent = $parent;
if (null !== $parent) {
//$parent->addChildren($this);
// $parent->addChildren($this);
}
return $this;
}
public function setIsCanceledAccompanyingPeriod(bool $isCanceledAP): ClosingMotive
{
$this->isCanceledAccompanyingPeriod = $isCanceledAP;
foreach ($this->getChildren() as $child) {
$child->setIsCanceledAccompanyingPeriod($isCanceledAP);
}
return $this;

View File

@@ -15,7 +15,6 @@ use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Serializer\Annotation\Groups;
@@ -23,7 +22,9 @@ use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period_comment")
*
* @DiscriminatorMap(typeProperty="type", mapping={
* "accompanying_period_comment": Comment::class
* })
@@ -34,48 +35,61 @@ class Comment implements TrackCreationInterface, TrackUpdateInterface
* @ORM\ManyToOne(
* targetEntity="Chill\PersonBundle\Entity\AccompanyingPeriod",
* inversedBy="comments")
*
* @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private ?AccompanyingPeriod $accompanyingPeriod = null;
/**
* @ORM\Column(type="text")
* @ORM\Column(type="text", nullable=false, options={"default":""})
*
* @Groups({"read", "write", "docgen:read"})
*
* @Assert\NotBlank
*
* @Assert\NotNull
*/
private ?string $content = null;
private string $content = '';
/**
* @ORM\Column(type="datetime")
*
* @Groups({"read", "docgen:read"})
*/
private ?DateTimeInterface $createdAt = null;
private ?\DateTimeInterface $createdAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=false)
*
* @Groups({"read", "docgen:read"})
*/
private ?User $creator = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="datetime")
*
* @Groups({"read"})
*/
private ?DateTimeInterface $updatedAt = null;
private ?\DateTimeInterface $updatedAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=false)
*
* @Groups({"read"})
*/
private ?User $updatedBy = null;
@@ -85,12 +99,12 @@ class Comment implements TrackCreationInterface, TrackUpdateInterface
return $this->accompanyingPeriod;
}
public function getContent(): ?string
public function getContent(): string
{
return $this->content;
}
public function getCreatedAt(): ?DateTimeInterface
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
@@ -105,7 +119,7 @@ class Comment implements TrackCreationInterface, TrackUpdateInterface
return $this->id;
}
public function getUpdatedAt(): ?DateTimeInterface
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
@@ -134,7 +148,7 @@ class Comment implements TrackCreationInterface, TrackUpdateInterface
return $this;
}
public function setCreatedAt(DateTimeInterface $createdAt): self
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
@@ -153,7 +167,7 @@ class Comment implements TrackCreationInterface, TrackUpdateInterface
return $this;
}
public function setUpdatedAt(DateTimeInterface $updatedAt): self
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;

View File

@@ -11,13 +11,14 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period_origin")
*
* @Serializer\DiscriminatorMap(
* typeProperty="type",
* mapping={
@@ -28,24 +29,30 @@ class Origin
{
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="json")
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Serializer\Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $label = [];
/**
* @ORM\Column(type="date_immutable", nullable=true)
*
* @Serializer\Groups({"read"})
*/
private ?DateTimeImmutable $noActiveAfter = null;
private ?\DateTimeImmutable $noActiveAfter = null;
public function getId(): ?int
{
@@ -57,7 +64,7 @@ class Origin
return $this->label;
}
public function getNoActiveAfter(): ?DateTimeImmutable
public function getNoActiveAfter(): ?\DateTimeImmutable
{
return $this->noActiveAfter;
}
@@ -69,7 +76,7 @@ class Origin
return $this;
}
public function setNoActiveAfter(?DateTimeImmutable $noActiveAfter): self
public function setNoActiveAfter(?\DateTimeImmutable $noActiveAfter): self
{
$this->noActiveAfter = $noActiveAfter;

View File

@@ -17,19 +17,21 @@ use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Serializer\Annotation\Groups;
use UnexpectedValueException;
/**
* **About denormalization**: this operation is operated by @see{AccompanyingPeriodResourdeNormalizer}.
*
* @ORM\Entity
*
* @ORM\Table(
* name="chill_person_accompanying_period_resource",
* uniqueConstraints={
*
* @ORM\UniqueConstraint(name="person_unique", columns={"person_id", "accompanyingperiod_id"}),
* @ORM\UniqueConstraint(name="thirdparty_unique", columns={"thirdparty_id", "accompanyingperiod_id"})
* }
* )
*
* @DiscriminatorMap(typeProperty="type", mapping={
* "accompanying_period_resource": Resource::class
* })
@@ -41,34 +43,43 @@ class Resource
* targetEntity="Chill\PersonBundle\Entity\AccompanyingPeriod",
* inversedBy="resources"
* )
*
* @ORM\JoinColumn(nullable=false)
*/
private ?AccompanyingPeriod $accompanyingPeriod = null;
/**
* @ORM\Column(type="text", nullable=true)
*
* @Groups({"read", "docgen:read"})
*/
private ?string $comment = '';
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\ManyToOne(targetEntity=Person::class)
*
* @ORM\JoinColumn(nullable=true)
*
* @Groups({"docgen:read"})
*/
private ?Person $person = null;
/**
* @ORM\ManyToOne(targetEntity=ThirdParty::class)
*
* @ORM\JoinColumn(nullable=true)
*
* @Groups({"docgen:read"})
*/
private ?ThirdParty $thirdParty = null;
@@ -94,10 +105,9 @@ class Resource
}
/**
* @return Person|ThirdParty
* @Groups({"read"})
*/
public function getResource()
public function getResource(): Person|ThirdParty|null
{
return $this->person ?? $this->thirdParty;
}
@@ -136,12 +146,7 @@ class Resource
$this->setPerson(null);
$this->setThirdParty(null);
} else {
throw new UnexpectedValueException(sprintf(
'the resource ' .
'should be an instance of %s or %s',
Person::class,
ThirdParty::class
));
throw new \UnexpectedValueException(sprintf('the resource should be an instance of %s or %s', Person::class, ThirdParty::class));
}
return $this;

View File

@@ -15,51 +15,50 @@ use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackCreationTrait;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*
* @ORM\Table("chill_person_accompanying_period_user_history")
*/
class UserHistory implements TrackCreationInterface
{
use TrackCreationTrait;
/**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class, inversedBy="userHistories")
* @ORM\JoinColumn(nullable=false)
*/
private ?AccompanyingPeriod $accompanyingPeriod;
/**
* @ORM\Column(type="datetime_immutable", nullable=true, options={"default": null})
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*/
private ?int $id = null;
/**
* @ORM\Column(type="datetime_immutable", nullable=false)
*/
private DateTimeImmutable $startDate;
public function __construct(
/**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class, inversedBy="userHistories")
*
* @ORM\JoinColumn(nullable=false)
*/
private ?AccompanyingPeriod $accompanyingPeriod,
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=false)
*/
private User $user,
/**
* @ORM\ManyToOne(targetEntity=User::class)
* @ORM\JoinColumn(nullable=false)
*/
private User $user;
public function __construct(AccompanyingPeriod $accompanyingPeriod, User $user, ?DateTimeImmutable $startDate = null)
{
$this->startDate = $startDate ?? new DateTimeImmutable('now');
$this->accompanyingPeriod = $accompanyingPeriod;
$this->user = $user;
/**
* @ORM\Column(type="datetime_immutable", nullable=false, options={"default": "now()"})
*/
private \DateTimeImmutable $startDate = new \DateTimeImmutable('now')
) {
}
public function getAccompanyingPeriod(): AccompanyingPeriod
@@ -67,7 +66,7 @@ class UserHistory implements TrackCreationInterface
return $this->accompanyingPeriod;
}
public function getEndDate(): ?DateTimeImmutable
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -77,7 +76,7 @@ class UserHistory implements TrackCreationInterface
return $this->id;
}
public function getStartDate(): DateTimeImmutable
public function getStartDate(): \DateTimeImmutable
{
return $this->startDate;
}
@@ -87,7 +86,7 @@ class UserHistory implements TrackCreationInterface
return $this->user;
}
public function setEndDate(?DateTimeImmutable $endDate): UserHistory
public function setEndDate(?\DateTimeImmutable $endDate): UserHistory
{
$this->endDate = $endDate;

View File

@@ -11,8 +11,6 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Entity;
use DateTime;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Serializer\Annotation\Groups;
@@ -21,51 +19,55 @@ use Symfony\Component\Serializer\Annotation\Groups;
* AccompanyingPeriodParticipation Class.
*
* @ORM\Entity
*
* @ORM\Table(name="chill_person_accompanying_period_participation")
*
* @DiscriminatorMap(typeProperty="type", mapping={
* "accompanying_period_participation": AccompanyingPeriodParticipation::class
* })
*/
class AccompanyingPeriodParticipation
{
/**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class, inversedBy="participations", cascade={"persist"})
* @ORM\JoinColumn(name="accompanyingperiod_id", referencedColumnName="id", nullable=false)
*/
private ?AccompanyingPeriod $accompanyingPeriod = null;
/**
* @ORM\Column(type="date", nullable=true)
*
* @Groups({"read", "docgen:read"})
*/
private ?DateTime $endDate = null;
private ?\DateTime $endDate = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\ManyToOne(targetEntity=Person::class, inversedBy="accompanyingPeriodParticipations")
* @ORM\JoinColumn(name="person_id", referencedColumnName="id", nullable=false)
* @Groups({"read", "docgen:read"})
*/
private ?Person $person = null;
/**
* @ORM\Column(type="date", nullable=false)
*
* @Groups({"read", "docgen:read"})
*/
private ?DateTime $startDate = null;
private ?\DateTime $startDate = null;
public function __construct(AccompanyingPeriod $accompanyingPeriod, Person $person)
{
$this->startDate = new DateTime('now');
$this->accompanyingPeriod = $accompanyingPeriod;
$this->person = $person;
public function __construct(/**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class, inversedBy="participations", cascade={"persist"})
*
* @ORM\JoinColumn(name="accompanyingperiod_id", referencedColumnName="id", nullable=false)
*/
private ?AccompanyingPeriod $accompanyingPeriod, /**
* @ORM\ManyToOne(targetEntity=Person::class, inversedBy="accompanyingPeriodParticipations")
*
* @ORM\JoinColumn(name="person_id", referencedColumnName="id", nullable=false)
*
* @Groups({"read", "docgen:read"})
*/
private ?Person $person
) {
$this->startDate = new \DateTime('now');
$person->getAccompanyingPeriodParticipations()->add($this);
}
@@ -74,7 +76,7 @@ class AccompanyingPeriodParticipation
return $this->accompanyingPeriod;
}
public function getEndDate(): ?DateTimeInterface
public function getEndDate(): ?\DateTimeInterface
{
return $this->endDate;
}
@@ -89,7 +91,7 @@ class AccompanyingPeriodParticipation
return $this->person;
}
public function getStartDate(): ?DateTimeInterface
public function getStartDate(): ?\DateTimeInterface
{
return $this->startDate;
}
@@ -106,7 +108,7 @@ class AccompanyingPeriodParticipation
return $this;
}
public function setEndDate(?DateTime $endDate): self
public function setEndDate(?\DateTime $endDate): self
{
$this->endDate = $endDate;

View File

@@ -11,33 +11,31 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Entity\Household;
use ArrayIterator;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Validator\Constraints\Household\MaxHolder;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\ReadableCollection;
use Doctrine\Common\Collections\Selectable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use function count;
/**
* @ORM\Entity
*
* @ORM\Table(
* name="chill_person_household"
* )
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "household": Household::class
* })
*
* @MaxHolder(groups={"household_memberships"})
*/
class Household
@@ -45,11 +43,16 @@ class Household
/**
* Addresses.
*
* @var Collection<Address>
*
* @ORM\ManyToMany(
* targetEntity="Chill\MainBundle\Entity\Address",
* cascade={"persist", "remove", "merge", "detach"})
*
* @ORM\JoinTable(name="chill_person_household_to_addresses")
*
* @ORM\OrderBy({"validFrom": "DESC", "id": "DESC"})
*
* @Serializer\Groups({"write"})
*/
private Collection $addresses;
@@ -60,45 +63,57 @@ class Household
private CommentEmbeddable $commentMembers;
/**
* @var Collection&Selectable<int, HouseholdComposition>
*
* @ORM\OneToMany(
* targetEntity=HouseholdComposition::class,
* mappedBy="household",
* orphanRemoval=true,
* cascade={"persist"}
* )
*
* @ORM\OrderBy({"startDate": "DESC"})
*
* @Assert\Valid(traverse=true, groups={"household_composition"})
*/
private Collection $compositions;
private Collection&Selectable $compositions;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @var Collection<HouseholdMember>
*
* @ORM\OneToMany(
* targetEntity=HouseholdMember::class,
* mappedBy="household"
* )
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private Collection $members;
/**
* @ORM\Column(type="boolean", name="waiting_for_birth", options={"default": false})
*
* @Serializer\Groups({"docgen:read"})
*/
private bool $waitingForBirth = false;
/**
* @ORM\Column(type="date_immutable", name="waiting_for_birth_date", nullable=true, options={"default": null})
*
* @Serializer\Groups({"docgen:read"})
*/
private ?DateTimeImmutable $waitingForBirthDate = null;
private ?\DateTimeImmutable $waitingForBirthDate = null;
public function __construct()
{
@@ -146,9 +161,9 @@ class Household
*
* @Assert\Callback(methods={"validate"})
*
* @return \Chill\MainBundle\Entity\Address[]
* @return Collection<Address>
*/
public function getAddresses()
public function getAddresses(): Collection
{
return $this->addresses;
}
@@ -196,11 +211,12 @@ class Household
/**
* @Serializer\Groups({"read", "docgen:read"})
*
* @Serializer\SerializedName("current_address")
*/
public function getCurrentAddress(?DateTime $at = null): ?Address
public function getCurrentAddress(?\DateTime $at = null): ?Address
{
$at ??= new DateTime('today');
$at ??= new \DateTime('today');
$addrs = $this->getAddresses()->filter(static fn (Address $a) => $a->getValidFrom() <= $at && (
null === $a->getValidTo() || $a->getValidTo() > $at
@@ -215,11 +231,12 @@ class Household
/**
* @Serializer\Groups({"docgen:read"})
*
* @Serializer\SerializedName("current_composition")
*/
public function getCurrentComposition(?DateTimeImmutable $at = null): ?HouseholdComposition
public function getCurrentComposition(?\DateTimeImmutable $at = null): ?HouseholdComposition
{
$at ??= new DateTimeImmutable('today');
$at ??= new \DateTimeImmutable('today');
$criteria = new Criteria();
$expr = Criteria::expr();
@@ -245,12 +262,12 @@ class Household
/**
* @Serializer\Groups({"docgen:read"})
*/
public function getCurrentMembers(?DateTimeImmutable $now = null): Collection
public function getCurrentMembers(?\DateTimeImmutable $now = null): Collection
{
return $this->getMembers()->matching($this->buildCriteriaCurrentMembers($now));
}
public function getCurrentMembersByPosition(Position $position, ?DateTimeInterface $now = null)
public function getCurrentMembersByPosition(Position $position, ?\DateTimeInterface $now = null)
{
$criteria = new Criteria();
$expr = Criteria::expr();
@@ -266,9 +283,10 @@ class Household
* Used in serialization
*
* @Serializer\Groups({"read"})
*
* @Serializer\SerializedName("current_members_id")
*/
public function getCurrentMembersIds(?DateTimeImmutable $now = null): ReadableCollection
public function getCurrentMembersIds(?\DateTimeImmutable $now = null): ReadableCollection
{
return $this->getCurrentMembers($now)->map(
static fn (HouseholdMember $m) => $m->getId()
@@ -278,22 +296,22 @@ class Household
/**
* @return HouseholdMember[]
*/
public function getCurrentMembersOrdered(?DateTimeImmutable $now = null): Collection
public function getCurrentMembersOrdered(?\DateTimeImmutable $now = null): Collection
{
$members = $this->getCurrentMembers($now);
$members->getIterator()
->uasort(
static function (HouseholdMember $a, HouseholdMember $b) {
if ($a->getPosition() === null) {
if ($b->getPosition() === null) {
if (null === $a->getPosition()) {
if (null === $b->getPosition()) {
return 0;
}
return -1;
}
if ($b->getPosition() === null) {
if (null === $b->getPosition()) {
return 1;
}
@@ -320,7 +338,7 @@ class Household
return $members;
}
public function getCurrentMembersWithoutPosition(?DateTimeInterface $now = null)
public function getCurrentMembersWithoutPosition(?\DateTimeInterface $now = null)
{
$criteria = new Criteria();
$expr = Criteria::expr();
@@ -337,7 +355,7 @@ class Household
*
* @return ReadableCollection<(int|string), Person>
*/
public function getCurrentPersons(?DateTimeImmutable $now = null): ReadableCollection
public function getCurrentPersons(?\DateTimeImmutable $now = null): ReadableCollection
{
return $this->getCurrentMembers($now)
->map(static fn (HouseholdMember $m) => $m->getPerson());
@@ -383,7 +401,7 @@ class Household
return $this->getMembers()->matching($criteria);
}
public function getMembersOnRange(DateTimeImmutable $from, ?DateTimeImmutable $to): ReadableCollection
public function getMembersOnRange(\DateTimeImmutable $from, ?\DateTimeImmutable $to): ReadableCollection
{
return $this->getMembers()->filter(static function (HouseholdMember $m) use ($from, $to) {
if (null === $m->getEndDate() && null !== $to) {
@@ -406,11 +424,11 @@ class Household
});
}
public function getNonCurrentMembers(?DateTimeImmutable $now = null): Collection
public function getNonCurrentMembers(?\DateTimeImmutable $now = null): Collection
{
$criteria = new Criteria();
$expr = Criteria::expr();
$date = $now ?? new DateTimeImmutable('today');
$date = $now ?? new \DateTimeImmutable('today');
$criteria
->where(
@@ -426,7 +444,7 @@ class Household
return $this->getMembers()->matching($criteria);
}
public function getNonCurrentMembersByPosition(Position $position, ?DateTimeInterface $now = null)
public function getNonCurrentMembersByPosition(Position $position, ?\DateTimeInterface $now = null)
{
$criteria = new Criteria();
$expr = Criteria::expr();
@@ -436,7 +454,7 @@ class Household
return $this->getNonCurrentMembers($now)->matching($criteria);
}
public function getNonCurrentMembersWithoutPosition(?DateTimeInterface $now = null)
public function getNonCurrentMembersWithoutPosition(?\DateTimeInterface $now = null)
{
$criteria = new Criteria();
$expr = Criteria::expr();
@@ -470,7 +488,7 @@ class Household
public function getPreviousAddressOf(Address $address): ?Address
{
$iterator = new ArrayIterator($this->getAddressesOrdered());
$iterator = new \ArrayIterator($this->getAddressesOrdered());
$iterator->rewind();
while ($iterator->valid()) {
@@ -492,7 +510,7 @@ class Household
return $this->waitingForBirth;
}
public function getWaitingForBirthDate(): ?DateTimeImmutable
public function getWaitingForBirthDate(): ?\DateTimeImmutable
{
return $this->waitingForBirthDate;
}
@@ -509,7 +527,7 @@ class Household
static fn (HouseholdComposition $a, HouseholdComposition $b) => $a->getStartDate() <=> $b->getStartDate()
);
$iterator = new ArrayIterator($compositionOrdered);
$iterator = new \ArrayIterator($compositionOrdered);
$iterator->rewind();
/** @var ?HouseholdComposition $previous */
@@ -531,7 +549,7 @@ class Household
public function makeAddressConsistent(): void
{
$iterator = new ArrayIterator($this->getAddressesOrdered());
$iterator = new \ArrayIterator($this->getAddressesOrdered());
$iterator->rewind();
@@ -593,7 +611,7 @@ class Household
*/
public function setForceAddress(Address $address)
{
$address->setValidFrom(new DateTime('today'));
$address->setValidFrom(new \DateTime('today'));
$this->addAddress($address);
}
@@ -604,7 +622,7 @@ class Household
return $this;
}
public function setWaitingForBirthDate(?DateTimeImmutable $waitingForBirthDate): self
public function setWaitingForBirthDate(?\DateTimeImmutable $waitingForBirthDate): self
{
$this->waitingForBirthDate = $waitingForBirthDate;
@@ -616,7 +634,7 @@ class Household
$addresses = $this->getAddresses();
$cond = true;
for ($i = 0; count($addresses) - 1 > $i; ++$i) {
for ($i = 0; \count($addresses) - 1 > $i; ++$i) {
if ($addresses[$i]->getValidFrom() !== $addresses[$i + 1]->getValidTo()) {
$cond = false;
$context->buildViolation('The address are not sequentials. The validFrom date of one address should be equal to the validTo date of the previous address.')
@@ -626,11 +644,11 @@ class Household
}
}
private function buildCriteriaCurrentMembers(?DateTimeImmutable $now = null): Criteria
private function buildCriteriaCurrentMembers(?\DateTimeImmutable $now = null): Criteria
{
$criteria = new Criteria();
$expr = Criteria::expr();
$date = $now ?? new DateTimeImmutable('today');
$date = $now ?? new \DateTimeImmutable('today');
$criteria
->where($expr->orX(

View File

@@ -16,16 +16,17 @@ use Chill\MainBundle\Doctrine\Model\TrackCreationTrait;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateTrait;
use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
*
* @ORM\Table(
* name="chill_person_household_composition"
* )
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "household_composition_type": HouseholdCompositionType::class
* })
@@ -43,46 +44,59 @@ class HouseholdComposition implements TrackCreationInterface, TrackUpdateInterfa
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Assert\GreaterThanOrEqual(propertyPath="startDate", groups={"Default", "household_composition"})
*
* @Serializer\Groups({"docgen:read"})
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\ManyToOne(targetEntity=Household::class, inversedBy="compositions")
*
* @ORM\JoinColumn(nullable=false)
*/
private ?Household $household = null;
/**
* @ORM\ManyToOne(targetEntity=HouseholdCompositionType::class)
*
* @ORM\JoinColumn(nullable=false)
*
* @Serializer\Groups({"docgen:read"})
*/
private ?HouseholdCompositionType $householdCompositionType = null;
private ?HouseholdCompositionType $householdCompositionType = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="integer", nullable=true, options={"default": null})
*
* @Assert\NotNull
*
* @Assert\GreaterThanOrEqual(0, groups={"Default", "household_composition"})
*
* @Serializer\Groups({"docgen:read"})
*/
private ?int $numberOfChildren = null;
/**
* @ORM\Column(type="date_immutable", nullable=false)
*
* @Assert\NotNull(groups={"Default", "household_composition"})
*
* @Serializer\Groups({"docgen:read"})
*/
private ?DateTimeImmutable $startDate = null;
private ?\DateTimeImmutable $startDate = null;
public function __construct()
{
@@ -94,7 +108,7 @@ class HouseholdComposition implements TrackCreationInterface, TrackUpdateInterfa
return $this->comment;
}
public function getEndDate(): ?DateTimeImmutable
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -119,7 +133,7 @@ class HouseholdComposition implements TrackCreationInterface, TrackUpdateInterfa
return $this->numberOfChildren;
}
public function getStartDate(): ?DateTimeImmutable
public function getStartDate(): ?\DateTimeImmutable
{
return $this->startDate;
}
@@ -131,7 +145,7 @@ class HouseholdComposition implements TrackCreationInterface, TrackUpdateInterfa
return $this;
}
public function setEndDate(?DateTimeImmutable $endDate): HouseholdComposition
public function setEndDate(?\DateTimeImmutable $endDate): HouseholdComposition
{
$this->endDate = $endDate;
@@ -163,7 +177,7 @@ class HouseholdComposition implements TrackCreationInterface, TrackUpdateInterfa
return $this;
}
public function setStartDate(?DateTimeImmutable $startDate): HouseholdComposition
public function setStartDate(?\DateTimeImmutable $startDate): HouseholdComposition
{
$this->startDate = $startDate;

View File

@@ -16,9 +16,11 @@ use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Entity
*
* @ORM\Table(
* name="chill_person_household_composition_type"
* )
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "household_composition_type": HouseholdCompositionType::class
* })
@@ -32,15 +34,20 @@ class HouseholdCompositionType
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="json")
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Serializer\Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $label = [];

View File

@@ -12,14 +12,13 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Entity\Household;
use Chill\PersonBundle\Entity\Person;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use LogicException;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
*
* @ORM\Table(
* name="chill_person_household_members"
* )
@@ -28,59 +27,71 @@ class HouseholdMember
{
/**
* @ORM\Column(type="string", length=255, nullable=true)
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?string $comment = null;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Assert\GreaterThanOrEqual(
* propertyPath="startDate",
* message="household_membership.The end date must be after start date",
* groups={"household_memberships"}
* )
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\Column(type="boolean", options={"default": false})
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private bool $holder = false;
/**
* @var Household
* @ORM\ManyToOne(
* targetEntity="\Chill\PersonBundle\Entity\Household\Household"
* )
*
* @Assert\Valid(groups={"household_memberships"})
*
* @Assert\NotNull(groups={"household_memberships"})
*/
private ?Household $household = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @var Person
* @ORM\ManyToOne(
* targetEntity="\Chill\PersonBundle\Entity\Person"
* )
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Serializer\Context({"docgen:person:with-household": false})
*
* @Assert\Valid(groups={"household_memberships"})
*
* @Assert\NotNull(groups={"household_memberships"})
*/
private ?Person $person = null;
/**
* @ORM\ManyToOne(targetEntity=Position::class)
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?Position $position = null;
@@ -92,17 +103,19 @@ class HouseholdMember
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Assert\NotNull(groups={"household_memberships"})
*/
private ?DateTimeImmutable $startDate = null;
private ?\DateTimeImmutable $startDate = null;
public function getComment(): ?string
{
return $this->comment;
}
public function getEndDate(): ?DateTimeImmutable
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -135,14 +148,14 @@ class HouseholdMember
return $this->shareHousehold;
}
public function getStartDate(): ?DateTimeImmutable
public function getStartDate(): ?\DateTimeImmutable
{
return $this->startDate;
}
public function isCurrent(?DateTimeImmutable $at = null): bool
public function isCurrent(?\DateTimeImmutable $at = null): bool
{
$at ??= new DateTimeImmutable('now');
$at ??= new \DateTimeImmutable('now');
return $this->getStartDate() < $at && (
null === $this->getEndDate() || $this->getEndDate() > $at
@@ -161,7 +174,7 @@ class HouseholdMember
return $this;
}
public function setEndDate(?DateTimeImmutable $endDate = null): self
public function setEndDate(?\DateTimeImmutable $endDate = null): self
{
$this->endDate = $endDate;
@@ -178,8 +191,7 @@ class HouseholdMember
public function setHousehold(?Household $household): self
{
if ($this->household instanceof Household) {
throw new LogicException('You cannot change household ' .
'on a membership');
throw new \LogicException('You cannot change household on a membership');
}
$this->household = $household;
@@ -190,8 +202,7 @@ class HouseholdMember
public function setPerson(?Person $person): self
{
if ($this->person instanceof Person) {
throw new LogicException('You cannot change person ' .
'on a membership');
throw new \LogicException('You cannot change person on a membership');
}
$this->person = $person;
@@ -203,8 +214,7 @@ class HouseholdMember
public function setPosition(?Position $position): self
{
if ($this->position instanceof Position && $this->position !== $position) {
throw new LogicException('The position is already set. You cannot change ' .
'a position of a membership');
throw new \LogicException('The position is already set. You cannot change a position of a membership');
}
$this->position = $position;
@@ -223,7 +233,7 @@ class HouseholdMember
return $this;
}
public function setStartDate(DateTimeImmutable $startDate): self
public function setStartDate(\DateTimeImmutable $startDate): self
{
$this->startDate = $startDate;

View File

@@ -13,8 +13,6 @@ namespace Chill\PersonBundle\Entity\Household;
use Chill\MainBundle\Entity\Address;
use Chill\PersonBundle\Entity\Person;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
/**
@@ -42,30 +40,37 @@ use Doctrine\ORM\Mapping as ORM;
* 3. 3st entity: from 2021-12-01 to NULL, household V, address T;
*
* @ORM\Entity(readOnly=true)
*
* @ORM\Table(name="view_chill_person_household_address")
*/
class PersonHouseholdAddress
{
/**
* @ORM\Id
*
* @ORM\ManyToOne(targetEntity=Address::class)
*
* @ORM\JoinColumn(nullable=false)
*/
private $address;
private ?Address $address = null;
/**
* @ORM\Id
*
* @ORM\ManyToOne(targetEntity=Household::class)
*
* @ORM\JoinColumn(nullable=false)
*/
private $household;
private ?Household $household = null;
/**
* @ORM\Id
*
* @ORM\ManyToOne(targetEntity=Person::class)
*
* @ORM\JoinColumn(nullable=false)
*/
private $person;
private ?Person $person = null;
/**
* @ORM\Column(type="date_immutable")
@@ -98,7 +103,7 @@ class PersonHouseholdAddress
* (this is not the startdate of the household, not
* the startdate of the address)
*/
public function getValidFrom(): ?DateTimeInterface
public function getValidFrom(): ?\DateTimeInterface
{
return $this->validFrom;
}
@@ -109,7 +114,7 @@ class PersonHouseholdAddress
* (this is not the enddate of the household, not
* the enddate of the address)
*/
public function getValidTo(): ?DateTimeImmutable
public function getValidTo(): ?\DateTimeImmutable
{
return $this->validTo;
}

View File

@@ -16,7 +16,9 @@ use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_person_household_position")
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "household_position": Position::class
* })
@@ -25,33 +27,41 @@ class Position
{
/**
* @ORM\Column(type="boolean")
*
* @Serializer\Groups({ "read" })
*/
private bool $allowHolder = false;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="json")
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Serializer\Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $label = [];
/**
* @ORM\Column(type="float")
*
* @Serializer\Groups({"read"})
*/
private float $ordering = 0.00;
/**
* @ORM\Column(type="boolean")
*
* @Serializer\Groups({"read"})
*/
private bool $shareHouseHold = true;

View File

@@ -17,15 +17,16 @@ use Doctrine\ORM\Mapping as ORM;
* MaritalStatus.
*
* @ORM\Entity
*
* @ORM\Table(name="chill_person_marital_status")
*
* @ORM\HasLifecycleCallbacks
*/
class MaritalStatus
{
/**
* @var string
*
* @ORM\Id
*
* @ORM\Column(type="string", length=7)
*/
private ?string $id;
@@ -60,8 +61,6 @@ class MaritalStatus
/**
* Set id.
*
* @return MaritalStatus
*/
public function setId(string $id): self
{
@@ -74,8 +73,6 @@ class MaritalStatus
* Set name.
*
* @param string array $name
*
* @return MaritalStatus
*/
public function setName(array $name): self
{

View File

@@ -11,9 +11,9 @@ declare(strict_types=1);
namespace Chill\PersonBundle\Entity;
use ArrayIterator;
use Chill\BudgetBundle\Entity\Charge;
use Chill\BudgetBundle\Entity\Resource;
use Chill\CalendarBundle\Entity\Calendar;
use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Entity\Address;
@@ -22,6 +22,7 @@ use Chill\MainBundle\Entity\Civility;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Entity\Embeddable\CommentEmbeddable;
use Chill\MainBundle\Entity\HasCenterInterface;
use Chill\MainBundle\Entity\Language;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Validation\Constraint\PhonenumberConstraint;
use Chill\PersonBundle\Entity\Household\Household;
@@ -35,27 +36,23 @@ use Chill\PersonBundle\Validator\Constraints\Household\HouseholdMembershipSequen
use Chill\PersonBundle\Validator\Constraints\Person\Birthdate;
use Chill\PersonBundle\Validator\Constraints\Person\PersonHasCenter;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Mapping as ORM;
use Exception;
use libphonenumber\PhoneNumber;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use UnexpectedValueException;
use function count;
use function in_array;
/**
* Person Class.
*
* @ORM\Entity
*
* @ORM\Table(name="chill_person_person",
* indexes={
*
* @ORM\Index(
* name="person_names",
* columns={"firstName", "lastName"}
@@ -65,35 +62,37 @@ use function in_array;
* columns={"birthdate"}
* )
* })
*
* @ORM\HasLifecycleCallbacks
*
* @DiscriminatorMap(typeProperty="type", mapping={
* "person": Person::class
* })
*
* @PersonHasCenter
*
* @HouseholdMembershipSequential(
* groups={"household_memberships"}
* )
*/
class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateInterface
class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateInterface, \Stringable
{
public const BOTH_GENDER = 'both';
final public const BOTH_GENDER = 'both';
// have days in commun
public const ERROR_ADDIND_PERIOD_AFTER_AN_OPEN_PERIOD = 2; // where there exist
final public const ERROR_ADDIND_PERIOD_AFTER_AN_OPEN_PERIOD = 2; // where there exist
public const ERROR_PERIODS_ARE_COLLAPSING = 1; // when two different periods
final public const ERROR_PERIODS_ARE_COLLAPSING = 1; // when two different periods
public const FEMALE_GENDER = 'woman';
final public const FEMALE_GENDER = 'woman';
public const MALE_GENDER = 'man';
final public const MALE_GENDER = 'man';
public const NO_INFORMATION = 'unknown';
final public const NO_INFORMATION = 'unknown';
/**
* Accept receiving email.
*
* @var bool
*
* @ORM\Column(type="boolean", options={"default": false})
*/
private ?bool $acceptEmail = false;
@@ -101,8 +100,6 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* Accept short text message (aka SMS).
*
* @var bool
*
* @ORM\Column(type="boolean", options={"default": false})
*/
private ?bool $acceptSMS = false;
@@ -110,14 +107,15 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* The person's accompanying periods (when the person was accompanied by the center).
*
* @var Collection
* @var Collection<AccompanyingPeriodParticipation>
*
* @ORM\OneToMany(targetEntity=AccompanyingPeriodParticipation::class,
* mappedBy="person",
* cascade={"persist", "remove", "merge", "detach"})
*
* @ORM\OrderBy({"startDate": "DESC"})
*/
private $accompanyingPeriodParticipations;
private Collection $accompanyingPeriodParticipations;
/**
* The accompanying period requested by the Person.
@@ -125,25 +123,27 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* @ORM\OneToMany(targetEntity=AccompanyingPeriod::class,
* mappedBy="requestorPerson")
*
* @var AccompanyingPeriod[]|Collection
* @var Collection<AccompanyingPeriod>
*/
private Collection $accompanyingPeriodRequested;
/**
* Addresses.
*
* @var Collection
* @var Collection<Address>
*
* @ORM\ManyToMany(
* targetEntity="Chill\MainBundle\Entity\Address",
* cascade={"persist", "remove", "merge", "detach"})
*
* @ORM\JoinTable(name="chill_person_persons_to_addresses")
*
* @ORM\OrderBy({"validFrom": "DESC"})
*/
private $addresses;
private Collection $addresses;
/**
* @var Collection
* @var Collection<PersonAltName>
*
* @ORM\OneToMany(
* targetEntity="Chill\PersonBundle\Entity\PersonAltName",
@@ -151,19 +151,20 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* cascade={"persist", "remove", "merge", "detach"},
* orphanRemoval=true)
*/
private $altNames;
private Collection $altNames;
/**
* The person's birthdate.
*
* @var DateTime
*
* @ORM\Column(type="date", nullable=true)
*
* @Birthdate
*/
private $birthdate;
private ?\DateTime $birthdate = null;
/**
* @var Collection<Charge>
*
* @ORM\OneToMany(
* targetEntity=Charge::class,
* mappedBy="person"
@@ -172,6 +173,8 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
private Collection $budgetCharges;
/**
* @var Collection<resource>
*
* @ORM\OneToMany(
* targetEntity=Resource::class,
* mappedBy="person"
@@ -180,6 +183,8 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
private Collection $budgetResources;
/**
* @var Collection<int, Calendar>
*
* @ORM\ManyToMany(
* targetEntity="Chill\CalendarBundle\Entity\Calendar",
* mappedBy="persons"
@@ -202,63 +207,57 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
private ?PersonCenterCurrent $centerCurrent = null;
/**
* @ORM\OneToMany(targetEntity=PersonCenterHistory::class, mappedBy="person", cascade={"persist"})
* @ORM\OneToMany(targetEntity=PersonCenterHistory::class, mappedBy="person", cascade={"persist", "remove"})
*
* @var Collection|PersonCenterHistory[]
* @var Collection<PersonCenterHistory>
*/
private Collection $centerHistory;
/**
* Array where customfield's data are stored.
*
* @var array
*
* @ORM\Column(type="json")
*/
private $cFData;
private ?array $cFData = null;
/**
* The marital status of the person.
*
* @var Civility
*
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Civility")
*
* @ORM\JoinColumn(nullable=true)
*/
private $civility;
private ?Civility $civility = null;
/**
* Contact information for contacting the person.
*
* @var string
*
* @ORM\Column(type="text", nullable=true)
*/
private $contactInfo = '';
private ?string $contactInfo = '';
/**
* The person's country of birth.
*
* @var Country
*
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Country")
*
* sf4 check: option inversedBy="birthsIn" return error mapping !!
*
* @ORM\JoinColumn(nullable=true)
*/
private $countryOfBirth;
private ?Country $countryOfBirth = null;
/**
* @ORM\Column(type="datetime", nullable=true, options={"default": NULL})
*/
private $createdAt;
private ?\DateTimeInterface $createdAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=true)
*/
private $createdBy;
private ?User $createdBy = null;
/**
* Cache the computation of household.
@@ -282,32 +281,32 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* The person's deathdate.
*
* @var DateTimeImmutable
*
* @ORM\Column(type="date_immutable", nullable=true)
*
* @Assert\Date
*
* @Assert\GreaterThanOrEqual(propertyPath="birthdate")
*
* @Assert\LessThanOrEqual("today")
*/
private ?DateTimeImmutable $deathdate = null;
private ?\DateTimeImmutable $deathdate = null;
/**
* The person's email.
*
* @var string
*
* @ORM\Column(type="text", nullable=true)
* @Assert\Email(
* checkMX=true
* )
*
* @Assert\Email()
*/
private $email = '';
private ?string $email = '';
/**
* The person's first name.
*
* @ORM\Column(type="string", length=255)
*
* @Assert\NotBlank(message="The firstname cannot be empty")
*
* @Assert\Length(
* max=255,
* )
@@ -320,17 +319,16 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*
* @ORM\Column(type="text", nullable=true)
*/
private string $fullnameCanonical = '';
private ?string $fullnameCanonical = '';
/**
* The person's gender.
*
* @var string
*
* @ORM\Column(type="string", length=9, nullable=true)
*
* @Assert\NotNull(message="The gender must be set")
*/
private $gender;
private ?string $gender = null;
/**
* Comment on gender.
@@ -342,6 +340,8 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* Read-only field, computed by the database.
*
* @var Collection<PersonHouseholdAddress>
*
* @ORM\OneToMany(
* targetEntity=PersonHouseholdAddress::class,
* mappedBy="person"
@@ -355,7 +355,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* mappedBy="person"
* )
*
* @var Collection|HouseholdMember[]
* @var Collection<HouseholdMember>
*/
private Collection $householdParticipations;
@@ -363,7 +363,9 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* The person's id.
*
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*/
private ?int $id = null;
@@ -372,7 +374,9 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* The person's last name.
*
* @ORM\Column(type="string", length=255)
*
* @Assert\NotBlank(message="The lastname cannot be empty")
*
* @Assert\Length(
* max=255,
* )
@@ -382,12 +386,11 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* The marital status of the person.
*
* @var MaritalStatus
*
* @ORM\ManyToOne(targetEntity="Chill\PersonBundle\Entity\MaritalStatus")
*
* @ORM\JoinColumn(nullable=true)
*/
private $maritalStatus;
private ?MaritalStatus $maritalStatus = null;
/**
* Comment on marital status.
@@ -399,26 +402,24 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* The date of the last marital status change of the person.
*
* @var DateTime
*
* @ORM\Column(type="date", nullable=true)
*
* @Assert\Date
*/
private ?DateTime $maritalStatusDate = null;
private ?\DateTime $maritalStatusDate = null;
/**
* A remark over the person.
*
* @var string
*
* @ORM\Column(type="text")
*/
private $memo = ''; // TO-CHANGE in remark
private string $memo = '';
/**
* The person's mobile phone number.
*
* @PhonenumberConstraint(type="mobile")
*
* @ORM\Column(type="phone_number", nullable=true)
*/
private ?PhoneNumber $mobilenumber = null;
@@ -426,27 +427,23 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* The person's nationality.
*
* @var Country
*
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Country")
*
* sf4 check: option inversedBy="nationals" return error mapping !!
*
* @ORM\JoinColumn(nullable=true)
*/
private $nationality;
private ?Country $nationality = null;
/**
* Number of children.
*
* @var int
*
* @ORM\Column(type="integer", nullable=true)
*/
private ?int $numberOfChildren = null;
/**
* @var Collection
* @var Collection<PersonPhone>
*
* @ORM\OneToMany(
* targetEntity="Chill\PersonBundle\Entity\PersonPhone",
@@ -454,17 +451,20 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* cascade={"persist", "remove", "merge", "detach"},
* orphanRemoval=true
* )
*
* @Assert\Valid(
* traverse=true,
* )
*/
private $otherPhoneNumbers;
private Collection $otherPhoneNumbers;
/**
* @ORM\OneToMany(
* targetEntity=AccompanyingPeriod::class,
* mappedBy="personLocation"
* )
*
* @var Collection<AccompanyingPeriod>
*/
private Collection $periodLocatedOn;
@@ -472,6 +472,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* The person's phonenumber.
*
* @ORM\Column(type="phone_number", nullable=true)
*
* @PhonenumberConstraint(
* type="landline",
* )
@@ -481,59 +482,57 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* The person's place of birth.
*
* @var string
*
* @ORM\Column(type="string", length=255, name="place_of_birth")
*/
private $placeOfBirth = '';
private string $placeOfBirth = '';
/**
* @var bool
*
* @deprecated
*
* @ORM\Column(type="boolean")
*/
private $proxyAccompanyingPeriodOpenState = false; //TO-DELETE ?
private bool $proxyAccompanyingPeriodOpenState = false; // TO-DELETE ?
/**
* @ORM\OneToMany(targetEntity=PersonResource::class, mappedBy="personOwner")
*
* @var Collection|PersonResource[];
* @var Collection<PersonResource>
*/
private Collection $resources;
/**
* The person's spoken languages.
*
* @var ArrayCollection
* @var Collection<Language>
*
* @ORM\ManyToMany(targetEntity="Chill\MainBundle\Entity\Language")
*
* @ORM\JoinTable(
* name="persons_spoken_languages",
* joinColumns={@ORM\JoinColumn(name="person_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="language_id", referencedColumnName="id")}
* )
*/
private $spokenLanguages;
private Collection $spokenLanguages;
/**
* @ORM\Column(type="datetime", nullable=true, options={"default": NULL})
*/
private $updatedAt;
private ?\DateTimeInterface $updatedAt = null;
/**
* @ORM\ManyToOne(
* targetEntity=User::class
* )
*/
private $updatedBy;
private ?User $updatedBy = null;
/**
* Person constructor.
*/
public function __construct()
{
$this->calendars = new ArrayCollection();
$this->accompanyingPeriodParticipations = new ArrayCollection();
$this->spokenLanguages = new ArrayCollection();
$this->addresses = new ArrayCollection();
@@ -551,10 +550,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
$this->centerHistory = new ArrayCollection();
}
/**
* @return string
*/
public function __toString()
public function __toString(): string
{
return $this->getLabel();
}
@@ -628,13 +624,13 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* the person are not collapsing (i.e. have not shared days) or having
* a period after an open period.
*
* @return true | array True if the accompanying periods are not collapsing,
* an array with data for displaying the error
* @return true|array True if the accompanying periods are not collapsing,
* an array with data for displaying the error
*/
public function checkAccompanyingPeriodsAreNotCollapsing()
public function checkAccompanyingPeriodsAreNotCollapsing(): array|bool
{
$periods = $this->getAccompanyingPeriodsOrdered();
$periodsNbr = count($periods);
$periodsNbr = \count($periods);
$i = 0;
while ($periodsNbr - 1 > $i) {
@@ -673,7 +669,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*
* To check if the Person and its accompanying period are consistent, use validation.
*
* @throws Exception if two lines of the accompanying period are open.
* @throws \Exception if two lines of the accompanying period are open
*/
public function close(?AccompanyingPeriod $accompanyingPeriod = null): void
{
@@ -713,7 +709,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
}
}
if (0 < count($closeCandidates)) {
if (0 < \count($closeCandidates)) {
return $closeCandidates[0];
}
@@ -737,7 +733,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* * as participant, only for opened participation;
*
* @param bool $asParticipantOpen add participation which are still opened
* @param bool $asRequestor add accompanying period where the person is requestor
* @param bool $asRequestor add accompanying period where the person is requestor
*
* @return AccompanyingPeriod[]|Collection
*/
@@ -749,8 +745,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
if ($asParticipantOpen) {
foreach ($this->getAccompanyingPeriodParticipations()
->map(fn (AccompanyingPeriodParticipation $app) => $app->getAccompanyingPeriod())
as $period
->map(fn (AccompanyingPeriodParticipation $app) => $app->getAccompanyingPeriod()) as $period
) {
if (!$result->contains($period)) {
$result->add($period);
@@ -775,7 +770,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
): int {
// TODO should be optimized to avoid loading accompanying period ?
return $this->getAccompanyingPeriodInvolved($asParticipantOpen, $asRequestor)
->filter(fn (AccompanyingPeriod $p) => $p->getStep() !== AccompanyingPeriod::STEP_DRAFT)
->filter(fn (AccompanyingPeriod $p) => AccompanyingPeriod::STEP_DRAFT !== $p->getStep())
->count();
}
@@ -805,7 +800,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
$accompanyingPeriods = [];
foreach ($this->accompanyingPeriodParticipations as $participation) {
/** @var AccompanyingPeriodParticipation $participation */
/* @var AccompanyingPeriodParticipation $participation */
$accompanyingPeriods[] = $participation->getAccompanyingPeriod();
}
@@ -819,7 +814,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
{
$periods = $this->getAccompanyingPeriods();
//order by date :
// order by date :
usort($periods, static function ($a, $b) {
$dateA = $a->getOpeningDate();
$dateB = $b->getOpeningDate();
@@ -857,17 +852,17 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*
* @deprecated since chill2.0, address is linked to the household. Use @see{Person::getCurrentHouseholdAddress}
*
* @throws Exception
* @throws \Exception
*/
public function getAddressAt(?DateTimeInterface $at = null): ?Address
public function getAddressAt(?\DateTimeInterface $at = null): ?Address
{
$at ??= new DateTime('now');
$at ??= new \DateTime('now');
if ($at instanceof DateTimeImmutable) {
$at = DateTime::createFromImmutable($at);
if ($at instanceof \DateTimeImmutable) {
$at = \DateTime::createFromImmutable($at);
}
/** @var ArrayIterator $addressesIterator */
/** @var \ArrayIterator $addressesIterator */
$addressesIterator = $this->getAddresses()
->filter(static fn (Address $address): bool => $address->getValidFrom() <= $at)
->getIterator();
@@ -895,12 +890,12 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*
* If the person has a deathdate, calculate the age at the deathdate.
*
* @param string $at A valid string to create a DateTime.
* @param string $at a valid string to create a DateTime
*/
public function getAge(string $at = 'now'): ?int
{
if ($this->birthdate instanceof DateTimeInterface) {
if ($this->deathdate instanceof DateTimeInterface) {
if ($this->birthdate instanceof \DateTimeInterface) {
if ($this->deathdate instanceof \DateTimeInterface) {
return (int) date_diff($this->birthdate, $this->deathdate)->format('%y');
}
@@ -915,7 +910,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this->altNames;
}
public function getBirthdate(): ?DateTime
public function getBirthdate(): ?\DateTime
{
return $this->birthdate;
}
@@ -936,6 +931,14 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this->budgetResources;
}
/**
* @return Collection<int, Calendar>
*/
public function getCalendars(): Collection
{
return $this->calendars;
}
public function getCenter(): ?Center
{
if (null !== $this->centerCurrent) {
@@ -991,7 +994,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this->countryOfBirth;
}
public function getCreatedAt(): ?DateTimeInterface
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
@@ -1019,7 +1022,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
public function getCurrentAccompanyingPeriods(): array
{
$currentAccompanyingPeriods = [];
$currentDate = new DateTime();
$currentDate = new \DateTime();
foreach ($this->accompanyingPeriodParticipations as $participation) {
$endDate = $participation->getEndDate();
@@ -1032,7 +1035,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $currentAccompanyingPeriods;
}
public function getCurrentHousehold(?DateTimeImmutable $at = null): ?Household
public function getCurrentHousehold(?\DateTimeImmutable $at = null): ?Household
{
$participation = $this->getCurrentHouseholdParticipationShareHousehold($at);
@@ -1047,11 +1050,11 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
* if the given date is 'now', use instead @see{getCurrentPersonAddress}, which is optimized on
* database side.
*/
public function getCurrentHouseholdAddress(?DateTimeImmutable $at = null): ?Address
public function getCurrentHouseholdAddress(?\DateTimeImmutable $at = null): ?Address
{
if (
null === $at
|| $at->format('Ymd') === (new DateTime('today'))->format('Ymd')
|| $at->format('Ymd') === (new \DateTime('today'))->format('Ymd')
) {
return $this->currentPersonAddress instanceof PersonCurrentAddress
? $this->currentPersonAddress->getAddress() : null;
@@ -1081,11 +1084,11 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return null;
}
public function getCurrentHouseholdParticipationShareHousehold(?DateTimeImmutable $at = null): ?HouseholdMember
public function getCurrentHouseholdParticipationShareHousehold(?\DateTimeImmutable $at = null): ?HouseholdMember
{
$criteria = new Criteria();
$expr = Criteria::expr();
$date = $at ?? new DateTimeImmutable('today');
$date = $at ?? new \DateTimeImmutable('today');
$datef = $date->format('Y-m-d');
if (
@@ -1125,7 +1128,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this->currentPersonAddress->getAddress();
}
public function getDeathdate(): ?DateTimeInterface
public function getDeathdate(): ?\DateTimeInterface
{
return $this->deathdate;
}
@@ -1165,19 +1168,12 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*/
public function getGenderNumeric()
{
switch ($this->getGender()) {
case self::FEMALE_GENDER:
return 1;
case self::MALE_GENDER:
return 0;
case self::BOTH_GENDER:
return 2;
default:
return -1;
}
return match ($this->getGender()) {
self::FEMALE_GENDER => 1,
self::MALE_GENDER => 0,
self::BOTH_GENDER => 2,
default => -1,
};
}
public function getHouseholdAddresses(): Collection
@@ -1209,7 +1205,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
->where(
$expr->eq('shareHousehold', false)
)
->orderBy(['startDate' => Criteria::DESC]);
->orderBy(['startDate' => \Doctrine\Common\Collections\Order::Descending]);
return $this->getHouseholdParticipations()
->matching($criteria);
@@ -1231,7 +1227,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
->where(
$expr->eq('shareHousehold', true)
)
->orderBy(['startDate' => Criteria::DESC, 'id' => Criteria::DESC]);
->orderBy(['startDate' => \Doctrine\Common\Collections\Order::Descending, 'id' => \Doctrine\Common\Collections\Order::Descending]);
return $this->getHouseholdParticipations()
->matching($criteria);
@@ -1247,20 +1243,20 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*/
public function getLabel()
{
return $this->getFirstName() . ' ' . $this->getLastName();
return $this->getFirstName().' '.$this->getLastName();
}
/**
* @deprecated Use @see{Person::getCurrentPersonAddress} or @see{Person::getCurrentHouseholdAddress} instead
*
* @throws Exception
*
* @return false|mixed|null
*
* @throws \Exception
*/
public function getLastAddress(?DateTime $from = null)
public function getLastAddress(?\DateTime $from = null)
{
return $this->getCurrentHouseholdAddress(
null !== $from ? DateTimeImmutable::createFromMutable($from) : null
null !== $from ? \DateTimeImmutable::createFromMutable($from) : null
);
}
@@ -1279,7 +1275,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this->maritalStatusComment;
}
public function getMaritalStatusDate(): ?DateTimeInterface
public function getMaritalStatusDate(): ?\DateTimeInterface
{
return $this->maritalStatusDate;
}
@@ -1309,7 +1305,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*/
public function getOpenedAccompanyingPeriod(): ?AccompanyingPeriod
{
if ($this->isOpen() === false) {
if (false === $this->isOpen()) {
return null;
}
@@ -1335,7 +1331,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
$criteria = Criteria::create();
$criteria
->andWhere(Criteria::expr()->eq('endDate', null))
->orWhere(Criteria::expr()->gt('endDate', new DateTime('now')));
->orWhere(Criteria::expr()->gt('endDate', new \DateTime('now')));
return $this->getAccompanyingPeriodParticipations()
->matching($criteria)
@@ -1360,7 +1356,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* @return PersonResource[]|Collection
*/
public function getResources()
public function getResources(): array|Collection
{
return $this->resources;
}
@@ -1368,14 +1364,14 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
/**
* Get spokenLanguages.
*
* @return ArrayCollection
* @return Collection<Language>
*/
public function getSpokenLanguages()
{
return $this->spokenLanguages;
}
public function getUpdatedAt(): ?DateTimeInterface
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
@@ -1385,7 +1381,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this->updatedBy;
}
public function hasCurrentHouseholdAddress(?DateTimeImmutable $at = null): bool
public function hasCurrentHouseholdAddress(?\DateTimeImmutable $at = null): bool
{
return null !== $this->getCurrentHouseholdAddress($at);
}
@@ -1401,7 +1397,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
foreach ($this->addresses as $ad) {
$validDate = $ad->getValidFrom()->format('Y-m-d');
if (in_array($validDate, $validYMDDates, true)) {
if (\in_array($validDate, $validYMDDates, true)) {
return true;
}
$validYMDDates[] = $validDate;
@@ -1472,7 +1468,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return false;
}
public function isSharingHousehold(?DateTimeImmutable $at = null): bool
public function isSharingHousehold(?\DateTimeImmutable $at = null): bool
{
return null !== $this->getCurrentHousehold($at);
}
@@ -1501,7 +1497,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
$participation = $this->participationsContainAccompanyingPeriod($accompanyingPeriod);
if (!null === $participation) {
$participation->setEndDate(new DateTime());
$participation->setEndDate(new \DateTime());
$this->accompanyingPeriodParticipations->removeElement($participation);
}
}
@@ -1566,7 +1562,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
}
/**
* @param DateTime $birthdate
* @param \DateTime $birthdate
*/
public function setBirthdate($birthdate): self
{
@@ -1582,7 +1578,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
*/
public function setCenter(?Center $center): self
{
$modification = new DateTimeImmutable('now');
$modification = new \DateTimeImmutable('now');
foreach ($this->centerHistory as $centerHistory) {
if (null === $centerHistory->getEndDate()) {
@@ -1606,9 +1602,16 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this;
}
/**
* @return Person
*/
public function addCenterHistory(PersonCenterHistory $newCenterHistory): self
{
if (!$this->centerHistory->contains($newCenterHistory)) {
$this->centerHistory[] = $newCenterHistory;
$newCenterHistory->setPerson($this);
}
return $this;
}
public function setCFData(?array $cFData): self
{
$this->cFData = $cFData;
@@ -1641,7 +1644,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this;
}
public function setCreatedAt(DateTimeInterface $datetime): self
public function setCreatedAt(\DateTimeInterface $datetime): self
{
$this->createdAt = $datetime;
@@ -1655,7 +1658,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this;
}
public function setDeathdate(?DateTimeInterface $deathdate): self
public function setDeathdate(?\DateTimeInterface $deathdate): self
{
$this->deathdate = $deathdate;
@@ -1718,7 +1721,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this;
}
public function setMaritalStatusDate(?DateTimeInterface $maritalStatusDate): self
public function setMaritalStatusDate(?\DateTimeInterface $maritalStatusDate): self
{
$this->maritalStatusDate = $maritalStatusDate;
@@ -1784,17 +1787,14 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
return $this;
}
/**
* @param Collection $spokenLanguages
*/
public function setSpokenLanguages($spokenLanguages): self
public function setSpokenLanguages(mixed $spokenLanguages): self
{
$this->spokenLanguages = $spokenLanguages;
return $this;
}
public function setUpdatedAt(DateTimeInterface $datetime): self
public function setUpdatedAt(\DateTimeInterface $datetime): self
{
$this->updatedAt = $datetime;
@@ -1815,7 +1815,7 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
}
$criteria = Criteria::create();
$now = new DateTimeImmutable('now');
$now = new \DateTimeImmutable('now');
$criteria->where(Criteria::expr()->lte('startDate', $now))
->andWhere(Criteria::expr()->orX(
Criteria::expr()->isNull('endDate'),
@@ -1824,16 +1824,11 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI
$histories = $this->centerHistory->matching($criteria);
switch ($histories->count()) {
case 0:
return null;
case 1:
return $histories->first();
default:
throw new UnexpectedValueException('It should not contains more than one center at a time');
}
return match ($histories->count()) {
0 => null,
1 => $histories->first(),
default => throw new \UnexpectedValueException('It should not contains more than one center at a time'),
};
}
/**

View File

@@ -13,7 +13,6 @@ namespace Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\Center;
use Chill\PersonBundle\Entity\Person;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
@@ -23,7 +22,9 @@ use Doctrine\ORM\Mapping as ORM;
* using a SQL view.
*
* @ORM\Entity(readOnly=true)
*
* @ORM\Table(name="view_chill_person_person_center_history_current")
*
* @psalm-internal Chill\PersonBundle\Entity
*/
class PersonCenterCurrent
@@ -36,10 +37,11 @@ class PersonCenterCurrent
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\Id
*
* @ORM\Column(type="integer")
*/
private ?int $id = null;
@@ -52,7 +54,7 @@ class PersonCenterCurrent
/**
* @ORM\Column(type="date_immutable", nullable=false)
*/
private DateTimeImmutable $startDate;
private \DateTimeImmutable $startDate;
/**
* Populate the properties person, center, start and end date from history.
@@ -75,7 +77,7 @@ class PersonCenterCurrent
return $this->center;
}
public function getEndDate(): ?DateTimeImmutable
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -93,7 +95,7 @@ class PersonCenterCurrent
return $this->person;
}
public function getStartDate(): DateTimeImmutable
public function getStartDate(): \DateTimeImmutable
{
return $this->startDate;
}

View File

@@ -17,13 +17,13 @@ use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateTrait;
use Chill\MainBundle\Entity\Center;
use Chill\PersonBundle\Entity\Person;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
* Associate a Person with a Center. The association may change on date intervals.
*
* @ORM\Entity
*
* @ORM\Table(name="chill_person_person_center_history")
*/
class PersonCenterHistory implements TrackCreationInterface, TrackUpdateInterface
@@ -32,38 +32,34 @@ class PersonCenterHistory implements TrackCreationInterface, TrackUpdateInterfac
use TrackUpdateTrait;
/**
* @ORM\ManyToOne(targetEntity=Center::class)
*/
private ?Center $center = null;
/**
* @ORM\Column(type="date_immutable", nullable=true, options={"default": null})
*/
private ?DateTimeImmutable $endDate = null;
private ?\DateTimeImmutable $endDate = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*/
private ?int $id = null;
/**
* @ORM\ManyToOne(targetEntity=Person::class, inversedBy="centerHistory")
*/
private ?Person $person = null;
/**
* @ORM\Column(type="date_immutable", nullable=false)
*/
private ?DateTimeImmutable $startDate = null;
public function __construct(?Person $person = null, ?Center $center = null, ?DateTimeImmutable $startDate = null)
{
$this->person = $person;
$this->center = $center;
$this->startDate = $startDate;
public function __construct(
/**
* @ORM\ManyToOne(targetEntity=Person::class, inversedBy="centerHistory")
*/
private ?Person $person = null,
/**
* @ORM\ManyToOne(targetEntity=Center::class)
*/
private ?Center $center = null,
/**
* @ORM\Column(type="date_immutable", nullable=false)
*/
private ?\DateTimeImmutable $startDate = null
) {
}
public function getCenter(): ?Center
@@ -71,7 +67,7 @@ class PersonCenterHistory implements TrackCreationInterface, TrackUpdateInterfac
return $this->center;
}
public function getEndDate(): ?DateTimeImmutable
public function getEndDate(): ?\DateTimeImmutable
{
return $this->endDate;
}
@@ -86,7 +82,7 @@ class PersonCenterHistory implements TrackCreationInterface, TrackUpdateInterfac
return $this->person;
}
public function getStartDate(): ?DateTimeImmutable
public function getStartDate(): ?\DateTimeImmutable
{
return $this->startDate;
}
@@ -98,7 +94,7 @@ class PersonCenterHistory implements TrackCreationInterface, TrackUpdateInterfac
return $this;
}
public function setEndDate(?DateTimeImmutable $endDate): self
public function setEndDate(?\DateTimeImmutable $endDate): self
{
$this->endDate = $endDate;
@@ -112,7 +108,7 @@ class PersonCenterHistory implements TrackCreationInterface, TrackUpdateInterfac
return $this;
}
public function setStartDate(?DateTimeImmutable $startDate): self
public function setStartDate(?\DateTimeImmutable $startDate): self
{
$this->startDate = $startDate;

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