]> Raphaƫl G. Git Repositories - packbundle/blobdiff - Util/FacebookUtil.php
Add alias and config members
[packbundle] / Util / FacebookUtil.php
index e2c891c84c98b5dcc28dd9ed25bb941e9dd44274..4def01be0b7b72016b5267a141ffb11e3666b83d 100644 (file)
 
 namespace Rapsys\PackBundle\Util;
 
+use Psr\Container\ContainerInterface;
+
+use Rapsys\PackBundle\RapsysPackBundle;
+
 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
 use Symfony\Component\Filesystem\Filesystem;
 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
@@ -21,71 +25,25 @@ use Symfony\Component\Routing\RouterInterface;
  */
 class FacebookUtil {
        /**
-        * The cache directory
-        *
-        * @var string
+        * Alias string
         */
-       protected $cache;
+       protected string $alias;
 
        /**
-        * The fonts array
-        *
-        * @var array
+        * Config array
         */
-       protected $fonts;
-
-       /**
-        * The public path
-        *
-        * @var string
-        */
-       protected $path;
-
-       /**
-        * The prefix
-        *
-        * @var string
-        */
-       protected $prefix;
-
-       /**
-        * The RouterInterface instance
-        */
-       protected RouterInterface $router;
-
-       /**
-        * The source
-        *
-        * @var string
-        */
-       protected $source;
+       protected array $config;
 
        /**
         * Creates a new facebook util
         *
+        * @param ContainerInterface $container The container instance
         * @param RouterInterface $router The RouterInterface instance
-        * @param string $cache The cache directory
-        * @param string $path The public path
-        * @param string $prefix The prefix
+        * @param SluggerUtil $slugger The SluggerUtil instance
         */
-       function __construct(RouterInterface $router, string $cache = '../var/cache', string $path = './bundles/rapsyspack', string $prefix = 'facebook', string $source = 'png/facebook.png', array $fonts = [ 'default' => 'ttf/default.ttf' ]) {
-               //Set cache
-               $this->cache = $cache.'/'.$prefix;
-
-               //Set fonts
-               $this->fonts = $fonts;
-
-               //Set path
-               $this->path = $path.'/'.$prefix;
-
-               //Set router
-               $this->router = $router;
-
-               //Set prefix key
-               $this->prefix = $prefix;
-
-               //Set source
-               $this->source = $source;
+       public function __construct(protected ContainerInterface $container, protected RouterInterface $router, protected SluggerUtil $slugger) {
+               //Retrieve config
+               $this->config = $container->getParameter($this->alias = RapsysPackBundle::getAlias());
        }
 
        /**
@@ -93,20 +51,44 @@ class FacebookUtil {
         *
         * Generate simple image in jpeg format or load it from cache
         *
-        * @param string $pathInfo The request path info
+        * @TODO: move to a svg merging system ?
+        *
+        * @param string $path The request path info
         * @param array $texts The image texts
         * @param int $updated The updated timestamp
         * @param ?string $source The image source
-        * @param int $width The width
-        * @param int $height The height
+        * @param ?int $height The height
+        * @param ?int $width The width
         * @return array The image array
         */
-       public function getImage(string $pathInfo, array $texts, int $updated, ?string $source = null, int $width = 1200, int $height = 630): array {
+       public function getImage(string $path, array $texts, int $updated, ?string $source = null, ?int $height = null, ?int $width = null): array {
+               //Without source
+               if ($source === null && $this->config['facebook']['source'] === null) {
+                       //Return empty image data
+                       return [];
+               //Without local source
+               } elseif ($source === null) {
+                       //Set local source
+                       $source = $this->config['facebook']['source'];
+               }
+
+               //Without width
+               if ($width === null) {
+                       //Set width from config
+                       $width = $this->config['facebook']['width'];
+               }
+
+               //Without height
+               if ($height === null) {
+                       //Set height from config
+                       $height = $this->config['facebook']['height'];
+               }
+
                //Set path file
-               $path = $this->path.$pathInfo.'.jpeg';
+               $facebook = $this->config['cache'].'/'.$this->config['prefixes']['facebook'].$path.'.jpeg';
 
                //Without existing path
-               if (!is_dir($dir = dirname($path))) {
+               if (!is_dir($dir = dirname($facebook))) {
                        //Create filesystem object
                        $filesystem = new Filesystem();
 
@@ -121,12 +103,18 @@ class FacebookUtil {
                }
 
                //With path file
-               if (is_file($path) && ($mtime = stat($path)['mtime']) && $mtime >= $updated) {
+               if (is_file($facebook) && ($mtime = stat($facebook)['mtime']) && $mtime >= $updated) {
                        #XXX: we used to drop texts with $data['canonical'] === true !!!
 
+                       //Set short path
+                       $short = $this->slugger->short($path);
+
+                       //Set hash
+                       $hash = $this->slugger->serialize([$short, $height, $width]);
+
                        //Return image data
                        return [
-                               'og:image' => $this->router->generate('rapsys_pack_facebook', ['mtime' => $mtime, 'path' => $pathInfo], UrlGeneratorInterface::ABSOLUTE_URL),
+                               'og:image' => $this->router->generate('rapsyspack_facebook', ['hash' => $hash, 'path' => $short, 'height' => $height, 'width' => $width, 'u' => $mtime], UrlGeneratorInterface::ABSOLUTE_URL),
                                'og:image:alt' => str_replace("\n", ' ', implode(' - ', array_keys($texts))),
                                'og:image:height' => $height,
                                'og:image:width' => $width
@@ -134,7 +122,7 @@ class FacebookUtil {
                }
 
                //Set cache path
-               $cache = $this->cache.$pathInfo.'.png';
+               $cache = $this->config['cache'].'/'.$this->config['prefixes']['facebook'].$path.'.png';
 
                //Without cache path
                if (!is_dir($dir = dirname($cache))) {
@@ -151,12 +139,6 @@ class FacebookUtil {
                        }
                }
 
-               //Without source
-               if ($source === null) {
-                       //Set source
-                       $source = realpath($this->source);
-               }
-
                //Create image object
                $image = new \Imagick();
 
@@ -177,7 +159,17 @@ class FacebookUtil {
                                }
                        }
 
+                       //Without source
+                       if (!is_file($source)) {
+                               //Throw error
+                               throw new \Exception(sprintf('Source file "%s" do not exists', $source));
+                       }
+
+                       //Convert to absolute path
+                       $source = realpath($source);
+
                        //Read image
+                       //XXX: Imagick::readImage only supports absolute path
                        $image->readImage($source);
 
                        //Crop using aspect ratio
@@ -214,24 +206,6 @@ class FacebookUtil {
                        'right' => \Imagick::ALIGN_RIGHT
                ];
 
-               //Set default font
-               $defaultFont = 'dejavusans';
-
-               //Set default align
-               $defaultAlign = 'center';
-
-               //Set default size
-               $defaultSize = 60;
-
-               //Set default stroke
-               $defaultStroke = '#00c3f9';
-
-               //Set default width
-               $defaultWidth = 15;
-
-               //Set default fill
-               $defaultFill = 'white';
-
                //Init counter
                $i = 1;
 
@@ -241,16 +215,16 @@ class FacebookUtil {
                //Draw each text stroke
                foreach($texts as $text => $data) {
                        //Set font
-                       $draw->setFont($this->fonts[$data['font']??$defaultFont]);
+                       $draw->setFont($this->config['fonts'][$data['font']??$this->config['facebook']['font']]);
 
                        //Set font size
-                       $draw->setFontSize($data['size']??$defaultSize);
+                       $draw->setFontSize($data['size']??$this->config['facebook']['size']);
 
                        //Set stroke width
-                       $draw->setStrokeWidth($data['width']??$defaultWidth);
+                       $draw->setStrokeWidth($data['thickness']??$this->config['facebook']['thickness']);
 
                        //Set text alignment
-                       $draw->setTextAlignment($align = ($aligns[$data['align']??$defaultAlign]));
+                       $draw->setTextAlignment($align = ($aligns[$data['align']??$this->config['facebook']['align']]));
 
                        //Get font metrics
                        $metrics = $image->queryFontMetrics($draw, $text);
@@ -278,10 +252,10 @@ class FacebookUtil {
                        $texts[$text]['y'] = $data['y'] += $metrics['ascender'] - $metrics['textHeight']/2;
 
                        //Set stroke color
-                       $draw->setStrokeColor(new \ImagickPixel($data['stroke']??$defaultStroke));
+                       $draw->setStrokeColor(new \ImagickPixel($data['border']??$this->config['facebook']['border']));
 
                        //Set fill color
-                       $draw->setFillColor(new \ImagickPixel($data['stroke']??$defaultStroke));
+                       $draw->setFillColor(new \ImagickPixel($data['fill']??$this->config['facebook']['fill']));
 
                        //Add annotation
                        $draw->annotation($data['x'], $data['y'], $text);
@@ -325,16 +299,16 @@ class FacebookUtil {
                //Draw each text
                foreach($texts as $text => $data) {
                        //Set font
-                       $draw->setFont($this->fonts[$data['font']??$defaultFont]);
+                       $draw->setFont($this->config['fonts'][$data['font']??$this->config['facebook']['font']]);
 
                        //Set font size
-                       $draw->setFontSize($data['size']??$defaultSize);
+                       $draw->setFontSize($data['size']??$this->config['facebook']['size']);
 
                        //Set text alignment
-                       $draw->setTextAlignment($aligns[$data['align']??$defaultAlign]);
+                       $draw->setTextAlignment($aligns[$data['align']??$this->config['facebook']['align']]);
 
                        //Set fill color
-                       $draw->setFillColor(new \ImagickPixel($data['fill']??$defaultFill));
+                       $draw->setFillColor(new \ImagickPixel($data['fill']??$this->config['facebook']['fill']));
 
                        //Add annotation
                        $draw->annotation($data['x'], $data['y'], $text);
@@ -359,14 +333,20 @@ class FacebookUtil {
                $image->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
 
                //Save image
-               if (!$image->writeImage($path)) {
+               if (!$image->writeImage($facebook)) {
                        //Throw error
-                       throw new \Exception(sprintf('Unable to write image "%s"', $path));
+                       throw new \Exception(sprintf('Unable to write image "%s"', $facebook));
                }
 
+               //Set short path
+               $short = $this->slugger->short($path);
+
+               //Set hash
+               $hash = $this->slugger->serialize([$short, $height, $width]);
+
                //Return image data
                return [
-                       'og:image' => $this->router->generate('rapsys_pack_facebook', ['mtime' => stat($path)['mtime'], 'path' => $pathInfo], UrlGeneratorInterface::ABSOLUTE_URL),
+                       'og:image' => $this->router->generate('rapsyspack_facebook', ['hash' => $hash, 'path' => $short, 'height' => $height, 'width' => $width, 'u' => stat($facebook)['mtime']], UrlGeneratorInterface::ABSOLUTE_URL),
                        'og:image:alt' => str_replace("\n", ' ', implode(' - ', array_keys($texts))),
                        'og:image:height' => $height,
                        'og:image:width' => $width