silverstripe-subsites/code/extensions/SiteConfigSubsites.php

75 lines
2.2 KiB
PHP
Raw Normal View History

2010-03-01 03:59:04 +01:00
<?php
2017-05-24 12:32:05 +02:00
namespace SilverStripe\Subsites\Extensions;
2016-09-22 16:38:29 +02:00
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HiddenField;
use SilverStripe\ORM\DataExtension;
2017-05-24 15:26:28 +02:00
use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\Queries\SQLSelect;
2017-05-24 13:36:04 +02:00
use SilverStripe\SiteConfig\SiteConfig;
2017-05-24 15:26:28 +02:00
use SilverStripe\Subsites\Model\Subsite;
2017-05-24 12:32:05 +02:00
2010-03-01 03:59:04 +01:00
/**
* Extension for the SiteConfig object to add subsites support
*/
2017-05-24 15:26:28 +02:00
class SiteConfigSubsites extends DataExtension
{
private static $has_one = [
'Subsite' => Subsite::class, // The subsite that this page belongs to
];
2017-05-24 15:26:28 +02:00
/**
* Update any requests to limit the results to the current site
2017-06-01 15:10:07 +02:00
* @param SQLSelect $query
* @param DataQuery|null $dataQuery
*/
public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
{
if (Subsite::$disable_subsite_filter) {
return;
}
2017-05-24 15:26:28 +02:00
// If you're querying by ID, ignore the sub-site - this is a bit ugly...
if ($query->filtersOnID()) {
return;
}
$regexp = '/^(.*\.)?("|`)?SubsiteID("|`)?\s?=/';
foreach ($query->getWhereParameterised($parameters) as $predicate) {
if (preg_match($regexp, $predicate)) {
return;
}
}
$subsiteID = (int)Subsite::currentSubsiteID();
2017-05-24 15:26:28 +02:00
$froms = $query->getFrom();
$froms = array_keys($froms);
$tableName = array_shift($froms);
if ($tableName !== SiteConfig::getSchema()->tableName(SiteConfig::class)) {
return;
}
$query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)");
}
2017-05-24 15:26:28 +02:00
2017-05-29 13:42:42 +02:00
public function onBeforeWrite()
2017-05-24 15:26:28 +02:00
{
if ((!is_numeric($this->owner->ID) || !$this->owner->ID) && !$this->owner->SubsiteID) {
$this->owner->SubsiteID = Subsite::currentSubsiteID();
}
}
/**
* Return a piece of text to keep DataObject cache keys appropriately specific
*/
2017-05-29 13:42:42 +02:00
public function cacheKeyComponent()
2017-05-24 15:26:28 +02:00
{
return 'subsite-' . Subsite::currentSubsiteID();
2017-05-24 15:26:28 +02:00
}
2017-05-29 13:42:42 +02:00
public function updateCMSFields(FieldList $fields)
2017-05-24 15:26:28 +02:00
{
$fields->push(new HiddenField('SubsiteID', 'SubsiteID', Subsite::currentSubsiteID()));
}
2010-03-01 03:59:04 +01:00
}