From 248faa7658a28f98d706f0c5362b1b4299308ff8 Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Mon, 18 Jul 2022 18:44:43 +1200 Subject: [PATCH] MNT Handle DatabaseExceptions thrown by PHP 8.1 --- src/PageTypes/DatedUpdateHolder.php | 59 ++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/src/PageTypes/DatedUpdateHolder.php b/src/PageTypes/DatedUpdateHolder.php index 54195d8d..0d24dd47 100644 --- a/src/PageTypes/DatedUpdateHolder.php +++ b/src/PageTypes/DatedUpdateHolder.php @@ -5,11 +5,13 @@ use DateTime; use Page; use SilverStripe\CMS\Model\SiteTree; +use SilverStripe\Control\Controller; use SilverStripe\Control\Director; use SilverStripe\Control\HTTP; use SilverStripe\Core\Config\Config; use SilverStripe\Core\Convert; use SilverStripe\ORM\ArrayList; +use SilverStripe\ORM\Connect\DatabaseException; use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\PaginatedList; @@ -146,6 +148,15 @@ public static function AllUpdates( )); } + try { + // Try running query inside try/catch block to handle any invalid date format + $items->dataQuery()->execute(); + } catch (DatabaseException $e) { + self::handleInvalidDateFormat($e); + // Ensure invalid SQL does not get run again + $items = $className::get()->limit(0); + } + // Unpaginated DataList. return $items; } @@ -185,20 +196,25 @@ public static function ExtractMonths( $link = Director::makeRelative($_SERVER['REQUEST_URI']); } - $dates = $updates->dataQuery() - ->groupby('YEAR("Date")') - ->groupby('MONTH("Date")') - ->query() - ->setSelect([ - 'Year' => 'YEAR("Date")', - 'Month' => 'MONTH("Date")', - ]) - ->addWhere('"Date" IS NOT NULL') - ->setOrderBy([ - 'YEAR("Date")' => 'DESC', - 'MONTH("Date")' => 'DESC', - ]) - ->execute(); + $dates = []; + try { + $dates = $updates->dataQuery() + ->groupby('YEAR("Date")') + ->groupby('MONTH("Date")') + ->query() + ->setSelect([ + 'Year' => 'YEAR("Date")', + 'Month' => 'MONTH("Date")', + ]) + ->addWhere('"Date" IS NOT NULL') + ->setOrderBy([ + 'YEAR("Date")' => 'DESC', + 'MONTH("Date")' => 'DESC', + ]) + ->execute(); + } catch (DatabaseException $e) { + self::handleInvalidDateFormat($e); + } $years = []; foreach ($dates as $date) { @@ -260,4 +276,19 @@ public function getSubscriptionTitle() { return $this->Title; } + + private static function handleInvalidDateFormat(DatabaseException $e): void + { + $controller = Controller::curr(); + if ($controller instanceof DatedUpdateHolderController && + strpos($e->getMessage(), 'Incorrect DATETIME value') !== false + ) { + $controller->getRequest()->getSession()->set(DatedUpdateHolderController::TEMP_FORM_MESSAGE, _t( + __CLASS__ . '.InvalidDateFormat', + 'Dates must be in "y-MM-dd" format.' + )); + } else { + throw $e; + } + } }