Skip to content

Instantly share code, notes, and snippets.

@remyzv
Forked from julienhay/ExampleController.php
Last active August 29, 2015 14:01
Show Gist options
  • Save remyzv/c258a6b689e75fe70bd8 to your computer and use it in GitHub Desktop.
Save remyzv/c258a6b689e75fe70bd8 to your computer and use it in GitHub Desktop.
<?php
App::uses('AppController', 'Controller');
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
App::uses('CakeTime', 'Utility');
class ExempleController extends AppController {
public function implementedEvents()
{
return parent::implementedEvents() + array(
'Crud.beforeSave' => '_beforeSave',
);
}
protected $accept_types = array(
'jpg' => 'image/jpeg',
'png' => 'image/png'
);
public function _beforeSave(CakeEvent $event)
{
$root_folder = 'files'.DS.'uploads/TONFOLDER';
$folder_site = new Folder($root_folder, true, 0755);
if ( !empty($this->request->data[$this->modelClass]['CHAMPS_FICHIER']['tmp_name']) && is_uploaded_file($this->request->data[$this->modelClass]['CHAMPS_FICHIER']['tmp_name']) )
{
$file_tmp = new File($this->request->data[$this->modelClass]['CHAMPS_FICHIER']['tmp_name']);
$type_mime = $file_tmp->mime();
if(in_array($file_tmp->mime(), $this->accept_types))
{
$file_origin = new File($this->request->data[$this->modelClass]['CHAMPS_FICHIER']['name']);
$filename = Inflector::slug($file_origin->name()).'.'.$file_origin->ext();
$file_real = new File($folder_site->path.DS.$filename);
$filename = $root_folder.$filename;
$this->testDuplicate($filename);
move_uploaded_file(
$this->data[$this->modelClass]['CHAMPS_FICHIER']['tmp_name'],
$filename
);
$this->request->data[$this->modelClass]['CHAMPS_FICHIER'] = $filename;
$this->request->data[$this->modelClass]['mime'] = $type_mime;
$this->request->data[$this->modelClass]['extfile'] = array_search($type_mime, $this->accept_types);
return true;
}
else
{
unset($this->request->data[$this->modelClass]['CHAMPS_FICHIER']);
$this->Session->setFlash(__('ONLY EXT, EXT AND EXT FILES'),'default',array('class' => 'error'));
if(isset($this->request->data[$this->modelClass]['id']))
{
$this->redirect(array(
'action' => 'edit',
$this->request->data[$this->modelClass]['id'],
));
}
else
{
$this->Session->write('data', $this->request->data);
$this->redirect(array(
'action' => 'add',
));
}
}
}
else
{
unset($this->request->data[$this->modelClass]['CHAMPS_FICHIER']);
return false;
}
}
/**
* If the file $dir already exists we add a {n} before the extension
**/
public function testDuplicate(&$dir,$count = 0){
$file = $dir;
if($count > 0){
$pathinfo = pathinfo($dir);
$file = $pathinfo['dirname'].'/'.$pathinfo['filename'].'-'.$count.'.'.$pathinfo['extension'];
}
if(!file_exists(WWW_ROOT.$file)){
$dir = $file;
}else{
$count++;
$this->testDuplicate($dir,$count);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment