diff --git a/src/Bundle/ChillPersonBundle/Entity/Person.php b/src/Bundle/ChillPersonBundle/Entity/Person.php index bf6a283c1..dc311ad07 100644 --- a/src/Bundle/ChillPersonBundle/Entity/Person.php +++ b/src/Bundle/ChillPersonBundle/Entity/Person.php @@ -910,9 +910,43 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI return $this->budgetResources; } + private function getCurrentCenterHistory(): ?PersonCenterHistory + { + if (0 === $this->centerHistory->count()) { + return null; + } + + $criteria = Criteria::create(); + $now = new DateTimeImmutable('now'); + $criteria->where(Criteria::expr()->lte('startDate', $now)) + ->andWhere(Criteria::expr()->orX( + Criteria::expr()->isNull('endDate'), + Criteria::expr()->gt('endDate', $now) + )); + + $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'); + } + } + public function getCenter(): ?Center { - return null === $this->centerCurrent ? null : $this->centerCurrent->getCenter(); + if (null !== $this->centerCurrent) { + return $this->centerCurrent->getCenter(); + } + + if (null === $currentCenterHistory = $this->getCurrentCenterHistory()) { + return null; + } + + return $currentCenterHistory->getCenter(); } public function getCFData(): ?array @@ -1544,7 +1578,6 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI } $this->centerHistory[] = $new = new PersonCenterHistory($this, $center, $modification); - $this->centerCurrent = new PersonCenterCurrent($new); return $this; } @@ -1572,7 +1605,15 @@ class Person implements HasCenterInterface, TrackCreationInterface, TrackUpdateI */ public function getCenterCurrent(): ?PersonCenterCurrent { - return $this->centerCurrent; + if (null !== $this->centerCurrent) { + return $this->centerCurrent; + } + + if (null === $currentCenterHistory = $this->getCurrentCenterHistory()) { + return null; + } + + return new PersonCenterCurrent($currentCenterHistory); } /**