mirror of
https://github.com/silverstripe/silverstripe-comments
synced 2024-10-22 11:05:49 +02:00
1900ab14b5
Enable comment moderation per-page
92 lines
2.5 KiB
PHP
92 lines
2.5 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Handles polymorphic relation for commentlist
|
|
*
|
|
* Uses elements of PolymorphicHasManyList in 3.2
|
|
*
|
|
* @author dmooyman
|
|
*/
|
|
class CommentList extends HasManyList {
|
|
|
|
/**
|
|
* Retrieve the name of the class this relation is filtered by
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getForeignClass() {
|
|
return $this->dataQuery->getQueryParam('Foreign.Class');
|
|
}
|
|
|
|
public function __construct($parentClassName) {
|
|
parent::__construct('Comment', 'ParentID');
|
|
|
|
|
|
// Ensure underlying DataQuery globally references the class filter
|
|
$this->dataQuery->setQueryParam('Foreign.Class', $parentClassName);
|
|
|
|
// For queries with multiple foreign IDs (such as that generated by
|
|
// DataList::relation) the filter must be generalised to filter by subclasses
|
|
$classNames = Convert::raw2sql(ClassInfo::subclassesFor($parentClassName));
|
|
$this->dataQuery->where(sprintf(
|
|
"\"BaseClass\" IN ('%s')", implode("', '", $classNames)
|
|
));
|
|
}
|
|
|
|
/**
|
|
* Adds the item to this relation.
|
|
*
|
|
* @param Comment $item The comment to be added
|
|
*/
|
|
public function add($item) {
|
|
// Check item given
|
|
if(is_numeric($item)) {
|
|
$item = Comment::get()->byID($item);
|
|
}
|
|
if(!($item instanceof Comment)) {
|
|
throw new InvalidArgumentException("CommentList::add() expecting a Comment object, or ID value");
|
|
}
|
|
|
|
// Validate foreignID
|
|
$foreignID = $this->getForeignID();
|
|
if(!$foreignID || is_array($foreignID)) {
|
|
throw new InvalidArgumentException("CommentList::add() can't be called until a single foreign ID is set");
|
|
}
|
|
|
|
$item->ParentID = $foreignID;
|
|
$item->BaseClass = $this->getForeignClass();
|
|
$item->write();
|
|
}
|
|
/**
|
|
* Remove a Comment from this relation by clearing the foreign key. Does not actually delete the comment.
|
|
*
|
|
* @param Comment $item The Comment to be removed
|
|
*/
|
|
public function remove($item) {
|
|
// Check item given
|
|
if(is_numeric($item)) {
|
|
$item = Comment::get()->byID($item);
|
|
}
|
|
if(!($item instanceof Comment)) {
|
|
throw new InvalidArgumentException("CommentList::remove() expecting a Comment object, or ID",
|
|
E_USER_ERROR);
|
|
}
|
|
|
|
// Don't remove item with unrelated class key
|
|
$foreignClass = $this->getForeignClass();
|
|
$classNames = ClassInfo::subclassesFor($foreignClass);
|
|
if(!in_array($item->BaseClass, $classNames)) return;
|
|
|
|
// Don't remove item which doesn't belong to this list
|
|
$foreignID = $this->getForeignID();
|
|
if( empty($foreignID)
|
|
|| (is_array($foreignID) && in_array($item->ParentID, $foreignID))
|
|
|| $foreignID == $item->ParentID
|
|
) {
|
|
$item->ParentID = null;
|
|
$item->BaseClass = null;
|
|
$item->write();
|
|
}
|
|
}
|
|
}
|