Skip to content

Instantly share code, notes, and snippets.

@goroba
Last active July 31, 2019 13:37
Show Gist options
  • Save goroba/c915afab5a5f0e5016b19af0f687d286 to your computer and use it in GitHub Desktop.
Save goroba/c915afab5a5f0e5016b19af0f687d286 to your computer and use it in GitHub Desktop.
Using UUID as identifier for SonataMediaBundle media entity. File path generates in `/context/year-month/day/filename.ext ` way.
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Sonata\MediaBundle\Entity\BaseMedia as BaseMedia;
/**
* @ORM\Entity(repositoryClass="App\Repository\MediaRepository")
*/
class Media extends BaseMedia
{
/**
* @ORM\Id
* @ORM\Column(name="id", type="guid")
* @ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
}
providers:
file:
generator: 'App\Bundles\Sonata\MediaBundle\Generator\UuidGenerator'
image:
generator: 'App\Bundles\Sonata\MediaBundle\Generator\UuidGenerator'
<?php
namespace App\Bundles\Sonata\MediaBundle\Generator;
use Ramsey\Uuid\Uuid;
use Sonata\MediaBundle\Model\MediaInterface;
use Sonata\MediaBundle\Generator\GeneratorInterface;
class UuidGenerator implements GeneratorInterface
{
/**
* {@inheritdoc}
*/
public function generatePath(MediaInterface $media)
{
$uuid = Uuid::fromString($media->getId());
/**
* You can also wrap levels with somthing linke md5() to
* encode date in path for end-users.
*/
$rep_first_level = ($uuid->getDateTime()->format('Y-m'));
$rep_second_level = ($uuid->getDateTime()->format('d'));
return sprintf('%s/%s/%s', $media->getContext(), $rep_first_level, $rep_second_level);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment