2016-07-06 46 views
3

雖然尋找到this question我想出了以下的解決方案,從canDelete()稱爲擴展到File找到,如果頁面上的精選形象已經改變

protected function isFileInUse() 
{ 
    $owner = $this->getOwner(); 
    $dataObjectSubClasses = ClassInfo::subclassesFor('DataObject'); 
    $classesWithFileHasOne = []; 
    foreach ($dataObjectSubClasses as $subClass) { 
     $hasOnes = array_flip($subClass::create()->hasOne()); 
     if (array_key_exists($owner->class, $hasOnes)) { 
      $classesWithFileHasOne[$subClass] = $hasOnes[$owner->class]; 
     } 
    } 

    $threshold = (Director::get_current_page()->class == 'AssetAdmin') ? 1 : 2; 
    $uses = 0; 
    foreach ($classesWithFileHasOne as $class => $relation) { 
     $uses += count($class::get()->filter("{$relation}ID", $this->owner->ID)); 
     if ($uses >= $threshold) { 
      return true; 
     } 
    } 

    return false; 
} 

有一個邊緣情況下,我不能讓儘管如此。如果某個特色圖像在博客文章中發生了變化,那麼如果只有一個其他圖像使用了相同的圖像,那麼採用這種方法後,它仍然會允許它被刪除。這是因爲在保存頁面之前,當前更改不會計入圖像的使用。

在CMS頁面和介質管理器中設置的閾值不同,以允許從使用該頁面的頁面中刪除圖像。

有沒有一種方法可以從我的文件擴展名中訪問包含頁面(或其他元素 - 我們使用Elemental)以查看其關聯圖像是否已更改?

回答

2

這是我最終想出的解決方案。我不完全滿意檢查請求,但看不到任何其他解決方案:

public function canDelete($member = null) 
{ 
    return !$this->isFileInUse(); 
} 

/** 
* Check if the file is in use anywhere on the site 
* @return bool True if the file is in use 
*/ 
protected function isFileInUse() 
{ 
    $owner = $this->getOwner(); 
    $dataObjectSubClasses = ClassInfo::subclassesFor('DataObject'); 
    $classesWithFileHasOne = []; 
    foreach ($dataObjectSubClasses as $subClass) { 
     $hasOnes = array_flip($subClass::create()->hasOne()); 
     if (array_key_exists($owner->class, $hasOnes)) { 
      $classesWithFileHasOne[$subClass] = $hasOnes[$owner->class]; 
     } 
    } 

    $threshold = ($this->isAssetAdmin() || ($this->isFileAttach($classesWithFileHasOne))) ? 1 : 2; 

    $uses = 0; 
    foreach ($classesWithFileHasOne as $class => $relation) { 
     $uses += count($class::get()->filter("{$relation}ID", $this->owner->ID)); 
     if ($uses >= $threshold) { 
      return true; 
     } 
    } 

    return false; 
} 

/** 
* Are we in the asset manager rather than editing a Page or Element? 
* @return bool 
*/ 
protected function isAssetAdmin() 
{ 
    return 'AssetAdmin' === Director::get_current_page()->class; 
} 

/** 
* Is the current action attaching a file to a field that we're interested in? 
* @param array $classesWithFileHasOne Classes with a relationship we're interested in and the name of the 
*          relevant field 
* @return bool 
*/ 
protected function isFileAttach($classesWithFileHasOne) 
{ 
    $controller = Controller::curr(); 
    $field = $controller->request->allParams()['FieldName']; 
    return (preg_match('/attach$/', $controller->requestParams['url']) && 
     ($controller->action == 'EditForm') 
     && (in_array($field, array_values($classesWithFileHasOne)))); 
} 
相關問題