Date overlapping when end date is null

I wrote a method within Doctrine to prevent overlapping of new dates that I want to add.

I have startDate and endDate there:

|---------------------|------------------|
|      startDate      |     endDate      |
|---------------------|------------------|
|      07-11-2020     |    13-11-2020    |
|---------------------|------------------|
|      14-11-2020     |    21-11-2020    |
|---------------------|------------------|

When I input 4-11 to 15-11 / Exception is thrown as it should

When I input 14-11 to 28-11 / *Exception is thrown as it should

When I add just startDate , as endDate is optional.., I add for example 14-11-2020 again it saves it successfully to the database even if I have it (as shown above)..

How to prevent that?

Method I use:

private function isOverlapping(BookSub $bookSub): bool
{
    $criteria = new Criteria();
    $criteria
        ->where($criteria->expr()->lt('startDate', $bookSub->getEndDate()))
        ->andWhere($criteria->expr()->gt('endDate', $bookSub->getStartDate()))
    ;
    $result = $this->entityManager->getRepository(BookSub::class)->matching($criteria);

    if ($result instanceof IteratorAggregate) {
        $result = $result->getIterator();
    }

    /* If no entity matched the query criteria or a single entity matched,
     * which is the same as the entity being validated, there are no
     * overlaps.
     */
    return 0 !== count($result);
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *