Created
March 7, 2011 22:07
-
-
Save mariuswilms/859371 to your computer and use it in GitHub Desktop.
Exemplaric beforeDelete hook for a file model, to delete corresponding version.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function beforeDelete($cascade = true) { | |
if (!$cascade) { | |
return true; | |
} | |
$result = $this->find('first', array( | |
'conditions' => array($this->primaryKey => $this->id), | |
'fields' => array('dirname', 'basename'), | |
'recursive' => -1 | |
)); | |
if (empty($result)) { | |
return false; | |
} | |
$pattern = MEDIA_FILTER . "*/"; | |
$pattern .= $result[$this->alias]['dirname'] . '/'; | |
$pattern .= pathinfo($result[$this->alias]['basename'], PATHINFO_FILENAME); | |
$files = glob("{$pattern}.*"); | |
$name = Mime_Type::guessName($result[$this->alias]['basename']); | |
$versions = array_keys(Configure::read('Media.filter.' . $name)); | |
if (count($files) > count($versions)) { | |
$message = 'MediaFile::beforeDelete - '; | |
$message .= "Pattern `{$pattern}` matched more than number of versions. "; | |
$message .= "Failing deletion of versions and record for `Media@{$this->id}`."; | |
CakeLog::write('warning', $message); | |
return false; | |
} | |
foreach ($files as $file) { | |
$File = new File($file); | |
if (!$File->delete()) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment