code: private function findStockUnits(StockSubjectInterface $subject)
      {
          /** @var StockUnitRepositoryInterface $repository */
          $repository = $this->entityManager->getRepository($subject::getStockUnitClass());
  
          /** @var StockUnitInterface[] $stockUnits */
          $stockUnits = array_merge(
              $repository->findNotClosedBySubject($subject),
              $repository->findLatestClosedBySubject($subject)
          );
  
          // Sort by "created/closed at" date desc
          usort($stockUnits, function (StockUnitInterface $a, StockUnitInterface $b) {
              if ($a->getState() === StockUnitStates::STATE_CLOSED && $b->getState() !== StockUnitStates::STATE_CLOSED) {
                  return 1;
              }
  
              if ($a->getState() !== StockUnitStates::STATE_CLOSED && $b->getState() === StockUnitStates::STATE_CLOSED) {
                  return -1;
              }
  
              if ($a->getState() === StockUnitStates::STATE_CLOSED && $b->getState() === StockUnitStates::STATE_CLOSED) {
                  $aDate = $a->getClosedAt()->getTimestamp();
                  $bDate = $b->getClosedAt()->getTimestamp();
  
                  if ($aDate > $bDate) {
                      return -1;
                  }
  
                  if ($aDate < $bDate) {
                      return 1;
                  }
              }
  
              $aDate = $a->getCreatedAt()->getTimestamp();
              $bDate = $b->getCreatedAt()->getTimestamp();
  
              if ($aDate > $bDate) {
                  return -1;
              }
  
              if ($aDate < $bDate) {
                  return 1;
              }
  
              return 0;
          });
  
          return $stockUnits;
      }
docs: Sorts the stock units.
  
  @param StockSubjectInterface $subject
  
  @return StockUnitInterface[]