ImageHandling.php 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Gregwar\ImageBundle\Services;
  3. use Gregwar\ImageBundle\ImageHandler;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. /**
  6. * Image manipulation service
  7. *
  8. * @author Gregwar <g.passault@gmail.com>
  9. */
  10. class ImageHandling
  11. {
  12. private $cache_dir;
  13. private $container;
  14. private $handler_class;
  15. public function __construct($cache_dir, $handler_class, ContainerInterface $container)
  16. {
  17. $this->cache_dir = $cache_dir;
  18. $this->handler_class = $handler_class;
  19. $this->container = $container;
  20. }
  21. /**
  22. * Get a manipulable image instance
  23. *
  24. * @param string $file the image path
  25. *
  26. * @return object a manipulable image instance
  27. */
  28. public function open($file)
  29. {
  30. return $this->createInstance($file);
  31. }
  32. /**
  33. * Get a new image
  34. *
  35. * @param $w the width
  36. * @param $h the height
  37. *
  38. * @return object a manipulable image instance
  39. */
  40. public function create($w, $h)
  41. {
  42. return $this->createInstance(null, $w, $h);
  43. }
  44. /**
  45. * Creates an instance defining the cache directory
  46. */
  47. private function createInstance($file, $w = null, $h = null)
  48. {
  49. $asset = $this->container->get('templating.helper.assets');
  50. $handler_class = $this->handler_class;
  51. $image = new $handler_class($file, $w, $h);
  52. $image->setCacheDir($this->cache_dir);
  53. $image->setFileCallback(function($file) use ($asset) {
  54. return $asset->getUrl($file);
  55. });
  56. return $image;
  57. }
  58. }