Skip to content

Instantly share code, notes, and snippets.

@defrag
Created November 26, 2012 10:12
Show Gist options
  • Save defrag/4147494 to your computer and use it in GitHub Desktop.
Save defrag/4147494 to your computer and use it in GitHub Desktop.
Sample Asset Manager handling upload
<?php
namespace RE\AssetBundle\Model;
use Knp\Bundle\GaufretteBundle\FilesystemMap;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Gaufrette\FileStream\Local;
use Gaufrette\StreamMode;
use RE\AssetBundle\Entity\Asset;
use RE\AssetBundle\Event\AssetProcessedEvent;
use Defrag\PluploadBundle\Model\UploaderInterface;
class AssetManager implements UploaderInterface {
protected $fs_map;
protected $fs;
protected $em;
protected $eventDispacher;
public function __construct(FilesystemMap $fs_map, EntityManager $em, EventDispatcher $eventDispacher)
{
$this->fs_map = $fs_map;
$this->fs = $this->fs_map->get('asset_fs');
$this->em = $em;
$this->eventDispacher = $eventDispacher;
}
public function upload(UploadedFile $file)
{
$a = $this->createAssetFromUploadedFile($file);
$this->em->persist($a);
$this->em->flush();
$name = $a->createUploadPath();
$a->createDirectoryPath();
$this->em->persist($a);
$this->em->flush();
$this->fs->write($name, file_get_contents($file->getPathname()));
$this->eventDispacher->dispatch('re.asset.asset_processed', new AssetProcessedEvent($a));
return array(
'id' => $a->getId(),
'originalFileName' => $a->getOriginalFileName(),
'path' => $a->getPath()
);
}
public function getFileSystem()
{
return $this->fs;
}
public function processThumbnails(Asset $asset)
{
//TODO: apply thumbnail processing
}
protected function createAssetFromUploadedFile(UploadedFile $file)
{
$a = new Asset();
$a
->setOriginalFileName($file->getClientOriginalName())
->setContentType($file->getClientMimeType())
->setFileSize($file->getClientSize())
->setExtension($file->guessExtension())
->createFileName()
;
return $a;
}
}
services:
re.asset_manager:
class: RE\AssetBundle\Model\AssetManager
arguments: [ "@knp_gaufrette.filesystem_map", "@doctrine.orm.entity_manager", "@event_dispatcher" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment