Skip to content

Instantly share code, notes, and snippets.

@wilr
Created September 14, 2022 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilr/947c8173e5c49d789d722b2f5a9d8b0c to your computer and use it in GitHub Desktop.
Save wilr/947c8173e5c49d789d722b2f5a9d8b0c to your computer and use it in GitHub Desktop.
A Silverstripe DataExtension which adds subsite support to the redirectedurls module.
SilverStripe\RedirectedURLs\Admin\RedirectedURLAdmin:
extensions:
- SilverStripe\Subsites\Extensions\SubsiteMenuExtension
SilverStripe\RedirectedURLs\Model\RedirectedURL:
extensions:
- SubsiteAwareRedirectExtension
<?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