Created
September 14, 2022 07:27
-
-
Save wilr/947c8173e5c49d789d722b2f5a9d8b0c to your computer and use it in GitHub Desktop.
A Silverstripe DataExtension which adds subsite support to the redirectedurls module.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SilverStripe\RedirectedURLs\Admin\RedirectedURLAdmin: | |
extensions: | |
- SilverStripe\Subsites\Extensions\SubsiteMenuExtension | |
SilverStripe\RedirectedURLs\Model\RedirectedURL: | |
extensions: | |
- SubsiteAwareRedirectExtension |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use SilverStripe\Forms\FieldList; | |
use SilverStripe\ORM\DataExtension; | |
use SilverStripe\ORM\DataQuery; | |
use SilverStripe\ORM\Queries\SQLSelect; | |
use SilverStripe\Subsites\Model\Subsite; | |
use SilverStripe\Subsites\State\SubsiteState; | |
class SubsiteAwareRedirectExtension extends DataExtension | |
{ | |
private static $has_one = [ | |
'Subsite' => Subsite::class, | |
]; | |
public function onBeforeWrite() | |
{ | |
if (!$this->owner->SubsiteID) { | |
$this->owner->SubsiteID = SubsiteState::singleton()->getSubsiteId(); | |
} | |
} | |
/** | |
* Update any requests to limit the results to the current site | |
* @param SQLSelect $query | |
* @param DataQuery|null $dataQuery | |
*/ | |
public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null) | |
{ | |
if (Subsite::$disable_subsite_filter) { | |
return; | |
} | |
if ($dataQuery && $dataQuery->getQueryParam('Subsite.filter') === false) { | |
return; | |
} | |
$subsiteID = SubsiteState::singleton()->getSubsiteId(); | |
if ($subsiteID === null) { | |
return; | |
} | |
// The foreach is an ugly way of getting the first key :-) | |
foreach ($query->getFrom() as $tableName => $info) { | |
$where = "\"$tableName\".\"SubsiteID\" IN ($subsiteID)"; | |
$query->addWhere($where); | |
break; | |
} | |
$sect = array_values($query->getSelect() ?? []); | |
$isCounting = strpos($sect[0] ?? '', 'COUNT') !== false; | |
// Ordering when deleting or counting doesn't apply | |
if (!$isCounting) { | |
$query->addOrderBy('"SubsiteID"'); | |
} | |
} | |
public function updateCMSFields(FieldList $fields) | |
{ | |
$fields->removeByName('SubsiteID'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment