Example #1
0
 /**
  * Handles the file upload process
  *
  * @param  string $newFileName Use this value (if not null) as the uploaded file's name
  *
  * @return Jabba_File
  * @throws Exception
  */
 public function handle()
 {
     $path = $this->getDirectory()->getPath();
     if (!is_writable($path)) {
         throw new \Exception("Server error: upload directory isn't writable.");
     }
     if (!$this->getHandler()) {
         throw new \Exception('No files were uploaded.');
     }
     $size = $this->getHandler()->getSize();
     if ($size == 0) {
         throw new \Exception('File is empty.');
     }
     if ($size > $this->getSizeLimit()) {
         throw new \Exception('File size exceeds maximum upload limit (' . $this->getSizeLimit() / 1024 . 'Kb).');
     }
     $pathinfo = pathinfo($this->getHandler()->getName());
     $fileName = $pathinfo['filename'];
     $ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
     if ($this->getAllowedExtensions() && !in_array(strtolower($ext), $this->getAllowedExtensions())) {
         $these = implode(', ', $this->getAllowedExtensions());
         throw new \Exception('File has an invalid extension, only files of type ' . $these . ' are allowed.');
     }
     $length = rand(7, 9);
     $uniqueId = File::getRandomString($length);
     $resource = File\Image::getPathByName($path, $uniqueId, 3, true) . $uniqueId . '.' . $ext;
     while (file_exists($resource)) {
         $resource = File\Image::getPathByName($path, $uniqueId, 3, true) . File::getRandomString($length) . '.' . $ext;
     }
     if ($this->getHandler()->save($resource)) {
         if (in_array($ext, array('jpg', 'jpeg', 'gif', 'png'))) {
             $file = new File\Image($resource);
         } else {
             $file = new File($resource);
         }
         return $file->setOriginalName($fileName);
     } else {
         throw new \Exception('Could not save the uploaded file');
     }
 }