Skip to content

Instantly share code, notes, and snippets.

@mariuswilms
Created March 7, 2011 22:07
Show Gist options
  • Save mariuswilms/859371 to your computer and use it in GitHub Desktop.
Save mariuswilms/859371 to your computer and use it in GitHub Desktop.
Exemplaric beforeDelete hook for a file model, to delete corresponding version.
<?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