Skip to content

Commit

Permalink
MNT Handle DatabaseExceptions thrown by PHP 8.1
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Jul 18, 2022
1 parent eea7d9e commit 248faa7
Showing 1 changed file with 45 additions and 14 deletions.
59 changes: 45 additions & 14 deletions src/PageTypes/DatedUpdateHolder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
}
}
}

0 comments on commit 248faa7

Please sign in to comment.