| 1 | <?php |
||
| 2 | |||
| 3 | namespace DNADesign\ElementalSubsites\Extensions; |
||
| 4 | |||
| 5 | use DNADesign\Elemental\Models\BaseElement; |
||
| 6 | use SilverStripe\Forms\FieldList; |
||
| 7 | use SilverStripe\Forms\HiddenField; |
||
| 8 | use SilverStripe\ORM\DataExtension; |
||
| 9 | use SilverStripe\ORM\DataObject; |
||
| 10 | use SilverStripe\ORM\DataQuery; |
||
| 11 | use SilverStripe\ORM\Queries\SQLSelect; |
||
| 12 | use SilverStripe\Subsites\Model\Subsite; |
||
| 13 | use SilverStripe\Subsites\State\SubsiteState; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * Make elements compatible with subsites |
||
| 17 | * Apply this extension to BaseElement |
||
| 18 | */ |
||
| 19 | class ElementalSubsiteExtension extends DataExtension |
||
| 20 | { |
||
| 21 | private static $has_one = [ |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 22 | 'Subsite' => Subsite::class, |
||
| 23 | ]; |
||
| 24 | |||
| 25 | public function updateCMSFields(FieldList $fields) |
||
| 26 | { |
||
| 27 | // add SubsiteID if Subsites is installed and Elemental has a subsite |
||
| 28 | if (class_exists(Subsite::class)) { |
||
| 29 | $fields->push( |
||
| 30 | HiddenField::create('SubsiteID', null, SubsiteState::singleton()->getSubsiteId()) |
||
| 31 | ); |
||
| 32 | } |
||
| 33 | } |
||
| 34 | |||
| 35 | |||
| 36 | /** |
||
| 37 | * Update any requests for elements to limit the results to the current site |
||
| 38 | * |
||
| 39 | * @param SQLSelect $query |
||
| 40 | * @param DataQuery|null $dataQuery |
||
| 41 | */ |
||
| 42 | public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null) |
||
| 43 | { |
||
| 44 | if (!class_exists(Subsite::class)) { |
||
| 45 | return; |
||
| 46 | } |
||
| 47 | |||
| 48 | if (Subsite::$disable_subsite_filter) { |
||
| 49 | return; |
||
| 50 | } |
||
| 51 | |||
| 52 | if ($dataQuery && $dataQuery->getQueryParam('Subsite.filter') === false) { |
||
|
0 ignored issues
–
show
|
|||
| 53 | return; |
||
| 54 | } |
||
| 55 | |||
| 56 | if ($query->filtersOnID()) { |
||
| 57 | return; |
||
| 58 | } |
||
| 59 | |||
| 60 | if (Subsite::$force_subsite) { |
||
| 61 | $subsiteID = Subsite::$force_subsite; |
||
| 62 | } else { |
||
| 63 | $subsiteID = (int) SubsiteState::singleton()->getSubsiteId(); |
||
| 64 | } |
||
| 65 | |||
| 66 | // Get the base table name |
||
| 67 | $elementTableName = DataObject::getSchema()->baseDataTable(BaseElement::class); |
||
| 68 | |||
| 69 | // The foreach is an ugly way of getting the first key :-) |
||
| 70 | foreach ($query->getFrom() as $tableName => $info) { |
||
| 71 | // The tableName should be Element or Element_Live... |
||
| 72 | if (substr($tableName, 0, strlen($elementTableName)) === $elementTableName) { |
||
| 73 | $query->addWhere("\"$tableName\".\"SubsiteID\" IN ($subsiteID)"); |
||
| 74 | break; |
||
| 75 | } |
||
| 76 | } |
||
| 77 | } |
||
| 78 | } |
||
| 79 |