diff --git a/api/src/Repositories/WorkingHoursRepository.php b/api/src/Repositories/WorkingHoursRepository.php index f210037..82c81d1 100644 --- a/api/src/Repositories/WorkingHoursRepository.php +++ b/api/src/Repositories/WorkingHoursRepository.php @@ -10,6 +10,7 @@ use Exception; use InvalidArgumentException; use PDO; use PDOException; +use PDOStatement; use TorstenHettstedt\TimekeepingApi\Models\ModelInterface; use TorstenHettstedt\TimekeepingApi\Models\WorkingHours; @@ -42,10 +43,33 @@ class WorkingHoursRepository implements RepositoryReaderInterface, RepositoryWri * @throws PDOException */ public function findAll(): array + { + return $this->findFiltered(null, null); + } + + /** + * + * Gibt alle vorhandenen Einträge zurück + * + * @param string|null $start + * @param string|null $end + * + * @return WorkingHours[] + * @throws Exception + */ + public function findFiltered(?string $start, ?string $end): array { $models = []; - $stmt = $this->database->prepare('select "Datum" as "workingDay", "Arbeitszeit" as "workingTime" from public."Arbeitszeiten" order by "Datum"'); - $stmt->execute(); + $stmt = $this->buildFindFilteredStatement($start, $end); + try { + $stmt->execute(); + } catch (PDOException $exception) { + if ($exception->getCode() === '22007' || $exception->getCode() === '22008') { + throw new RepositoryBadWhereDataException($exception); + } + throw $exception; + } + while ($row = $stmt->fetch()) { $model = new WorkingHours(); $model @@ -56,6 +80,35 @@ class WorkingHoursRepository implements RepositoryReaderInterface, RepositoryWri return $models; } + protected function buildFilterString(?string $start, ?string $end): string + { + if (is_string($start) && is_string($end)) { + return 'where "Datum" >= :start AND "Datum" <= :end '; + } + if (is_string($start)) { + return 'where "Datum" >= :start '; + } + if (is_string($end)) { + return 'where "Datum" <= :end '; + } + return ''; + } + + protected function buildFindFilteredStatement(?string $start, ?string $end): ?PDOStatement + { + $query = 'select "Datum" as "workingDay", "Arbeitszeit" as "workingTime" from public."Arbeitszeiten" '; + $query .= $this->buildFilterString($start, $end); + $query .= 'order by "Datum"'; + $stmt = $this->database->prepare($query); + if (is_string($start)) { + $stmt->bindParam(':start', $start); + } + if (is_string($end)) { + $stmt->bindParam(':end', $end); + } + return $stmt ?? null; + } + /** * Gibt den Eintrag zurück, der durch die ID *