silverstripe-comments/code/model/CommentList.php

99 lines
3.0 KiB
PHP
Raw Normal View History

<?php
/**
* Handles polymorphic relation for commentlist
*
* Uses elements of PolymorphicHasManyList in 3.2
*
* @author dmooyman
*/
2016-02-19 01:48:25 +01:00
class CommentList extends HasManyList
{
2016-02-19 01:48:25 +01:00
/**
* Retrieve the name of the class this relation is filtered by
*
* @return string
*/
public function getForeignClass()
{
return $this->dataQuery->getQueryParam('Foreign.Class');
}
2016-02-19 01:48:25 +01:00
public function __construct($parentClassName)
{
parent::__construct('Comment', 'ParentID');
2016-02-19 01:48:25 +01:00
// Ensure underlying DataQuery globally references the class filter
$this->dataQuery->setQueryParam('Foreign.Class', $parentClassName);
2016-02-19 01:48:25 +01:00
// 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)
));
}
2016-02-19 01:48:25 +01:00
/**
* 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");
}
2016-02-19 01:48:25 +01:00
$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();
}
}
}