Created
April 26, 2013 19:41
-
-
Save ZhukV/5469816 to your computer and use it in GitHub Desktop.
Abstract attach model for upload files in Symfony 2
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 | |
namespace Acme\DemoBundle\Model; | |
use Symfony\Component\HttpFoundation\File\UploadedFile; | |
/** | |
* Abstract class for control attachments model (Image, flash, other files) | |
* | |
* For upload files in your entity please usage ORM\HasLifecycleCallbacks (preUpdate, prePersist) | |
* Example: | |
* // @var string|UploadedFile | |
* protected $image; | |
* | |
* | |
* // ORM\PreUpdate | |
* // ORM\PrePersist | |
* public function uploadMyFile() | |
* { | |
* $movedPath = $this->uploadFile($this->image); | |
* if ($movedPath !== false) { | |
* $this->image = $movedPath | |
* } | |
* } | |
* | |
* // Get upload directory | |
* protected function getUploadPath() | |
* { | |
* return '/my-path' | |
* } | |
*/ | |
abstract class AttachModel | |
{ | |
/** | |
* Get upload path | |
* | |
* @return string | |
*/ | |
abstract protected function getUploadPath(); | |
/** | |
* Get web upload path | |
* | |
* @param null|string $uploadPath | |
* @return string | |
*/ | |
public function getFullUploadPath($uploadPath = null) | |
{ | |
return '/uploads' . ($uploadPath === null ? $this->getUploadPath() : $uploadPath); | |
} | |
/** | |
* Get root web path | |
* | |
* @return string | |
*/ | |
protected function getRootWebPath() | |
{ | |
return realpath(__DIR__ . '/../../../../web'); | |
} | |
/** | |
* Upload file | |
* | |
* @param string|UploadedFile $file | |
* @param string $uploadPath | |
* @param string $fileName | |
* @return bool|string | |
*/ | |
protected function uploadFile($file, $uploadPath = null, $fileName = null) | |
{ | |
if (!$file instanceof UploadedFile) { | |
return false; | |
} | |
if (null === $fileName) { | |
if(null === $ext = $file->guessExtension()) { | |
$ext = $file->getExtension(); | |
} | |
$fileName = sha1(uniqid(mt_rand(), true)); | |
if (null !== $ext) { | |
$fileName .= '.' . $ext; | |
} | |
} | |
$fullUploadPath = $this->getFullUploadPath($uploadPath); | |
$rootPath = $this->getRootWebPath(); | |
$movePath = $rootPath . $fullUploadPath; | |
$file->move($movePath, $fileName); | |
return $fullUploadPath . '/' . $fileName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment