Skip to content

Instantly share code, notes, and snippets.

@maximecolin
Last active December 17, 2020 10:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maximecolin/6d181c8585ab9d407029 to your computer and use it in GitHub Desktop.
Save maximecolin/6d181c8585ab9d407029 to your computer and use it in GitHub Desktop.
Faker uploaded file provider
Acme\Entity\Upload:
upload_fix:
file: <upload('fixtures/files/image-1.jpg')>
upload_random:
file: |
<upload(array(
'fixtures/files/image-1.jpg',
'fixtures/files/image-2.jpg',
'fixtures/files/image-3.jpg',
'fixtures/files/image-4.jpg',
'fixtures/files/image-5.jpg',
))>
<?php
namespace Acme\DemoBundle\Fixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Nelmio\Alice\Fixtures;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
/**
* Load data
*/
class LoadData implements FixtureInterface, ContainerAwareInterface
{
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface Container
*/
private $container;
/**
* {@inheritdoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
Fixtures::load(
array(
__DIR__.'/fixtures.yml',
),
$manager,
array(
'providers' => array($this)
)
);
}
/**
* Generate a fake UploadedFile
*
* This method works for all upload based on Doctrine events
*/
public function upload($filename)
{
if (is_array($filename)) {
$filename = \Faker\Provider\Base::randomElement($filename);
}
$path = sprintf('/tmp/%s', uniqid());
$copy = copy($filename, $path);
if (!$copy) {
throw new \Exception('Copy failed');
}
$mimetype = MimeTypeGuesser::getInstance()->guess($path);
$size = filesize($path);
$file = new UploadedFile($path, $filename, $mimetype, $size, null, true);
return $file;
}
}
<?php
namespace Acme\Entity;
/**
* @ORM\Table(name="upload")
* @ORM\Entity
* @Vich\Uploadable
*/
class Upload
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Vich\UploadableField(mapping="photo", fileNameProperty="filename")
*/
private $file;
/**
* @ORM\Column(name="filename", type="string", length=255, nullable=true)
*/
private $filename;
/**
* @ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
public function setFile(File $file = null)
{
$this->file = $file;
$this->updatedAt = new \DateTime();
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment