Advertisement
Guest User

Untitled

a guest
Jul 29th, 2020
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.69 KB | None | 0 0
  1. <?php namespace App\Entities;
  2.  
  3. /**
  4.  * Сущность HTML-тэга изображения
  5.  *
  6.  * @package App\Entities
  7.  * taburetka.ua
  8.  */
  9.  
  10. class HtmlImage
  11. {
  12.     /**
  13.      * Атрибуты
  14.      *
  15.      * @var array
  16.      */
  17.     protected $attributes = [];
  18.  
  19.     /**
  20.      * Сущность изображения
  21.      *
  22.      * @var Image
  23.      */
  24.     protected $entity;
  25.  
  26.     /**
  27.      * Индикатор ленивой загрузки
  28.      *
  29.      * @var bool
  30.      */
  31.     protected $lazy = false;
  32.  
  33.     /**
  34.      * Обычный источник
  35.      *
  36.      * @var
  37.      */
  38.     protected $src;
  39.  
  40.     /**
  41.      * Непережатый источник
  42.      *
  43.      * @var
  44.      */
  45.     protected $uncompressed;
  46.  
  47.     /**
  48.      * Конструктор
  49.      *
  50.      * @param Image|string $src
  51.      */
  52.     public function __construct($src)
  53.     {
  54.         // Нам передали строку?
  55.         if (is_string($src)) {
  56.  
  57.             // Для начала удаляем хост табуретки из URL
  58.             $src = preg_replace('/(http:|https:)?\/\/(([^\.]+)?\.)?taburetka\.([^\/]+)\//i', '', $src);
  59.  
  60.             // Если после этого не осталось URL
  61.             if (strpos($src, '//') !== 0 and strpos($src, 'http') !== 0) {
  62.  
  63.                 // Убираем QueryString
  64.                 $file = strtok($src, '?');
  65.  
  66.                 // Затем очищаем пробелы с концов
  67.                 $file = trim($file);
  68.  
  69.                 // Теперь убираем слєш в начала
  70.                 $file = ltrim($file, '/');
  71.  
  72.                 // Создадим сущность
  73.                 $src = new Image($file);
  74.             }
  75.         }
  76.  
  77.         // Удалось создать сущность изображения?
  78.         if ($src instanceof Image) {
  79.  
  80.             // Сохраняем сущность
  81.             $this->entity = $src;
  82.  
  83.             // Получим URL
  84.             $this->src = $this->attributes['src'] = $src->src();
  85.  
  86.             // Получим непережатый URL
  87.             $this->uncompressed = $src->unprocessed();
  88.  
  89.         // Иначе
  90.         } else {
  91.  
  92.             // Сохраняем атрибут как есть
  93.             $this->src = $this->attributes['src'] = $src;
  94.         }
  95.  
  96.         // Сохраняем настройку ленивой загрузки
  97.         $this->lazy = (bool) config('image.lazy', false);
  98.     }
  99.  
  100.     /**
  101.      * Задает значение атрибута
  102.      *
  103.      * @param string $attr
  104.      * @param mixed|null $value
  105.      * @return $this
  106.      */
  107.     public function attr(string $attr, $value = null)
  108.     {
  109.         $this->attributes[$attr] = $value;
  110.         return $this;
  111.     }
  112.  
  113.     /**
  114.      * Принудительное выключение ленивой загрузки
  115.      *
  116.      * @return $this
  117.      */
  118.     public function eager()
  119.     {
  120.         $this->lazy = false;
  121.         return $this;
  122.     }
  123.  
  124.     /**
  125.      * Принудительное включение ленивой загрузки
  126.      *
  127.      * @return $this
  128.      */
  129.     public function lazy()
  130.     {
  131.         $this->lazy = true;
  132.         return $this;
  133.     }
  134.  
  135.     /**
  136.      * Запрещает испльзвание пережатых картинок
  137.      *
  138.      * @return $this
  139.      */
  140.     public function unprocessed()
  141.     {
  142.         if (array_key_exists('src', $this->attributes)) {
  143.             $this->attributes['src'] = $this->uncompressed ?: $this->attributes['src'];
  144.         }
  145.         return $this;
  146.     }
  147.  
  148.     /**
  149.      * Получает массив готовых атрибутов
  150.      *
  151.      * @param array|null $attrs
  152.      * @return mixed
  153.      */
  154.     public function attrs(array $attrs = null)
  155.     {
  156.         // Если переданы атрибуты
  157.         if ($attrs !== null) {
  158.  
  159.             // Добавляем их
  160.             $this->attributes = array_merge($this->attributes, $attrs);
  161.  
  162.             // Позволяем делать чейн
  163.             return $this;
  164.         }
  165.  
  166.         // Бекапим атрибуты
  167.         $attributes = $this->attributes;
  168.  
  169.         // Если включена ленивая загрузка
  170.         if ($this->lazy) {
  171.  
  172.             // Задаем адрес ленивой загрузки
  173.             $attributes['data-src'] = $attributes['src'];
  174.  
  175.             // Подменяем тэг иточника
  176.             $attributes['src'] = config('image.placeholder');
  177.  
  178.           // Добавляем класс ленивой загрузки
  179.             $attributes['class'] = 'lazyload';
  180.         }
  181.  
  182.         // Если задан title но нет alt
  183.         if (isset($attributes['title']) and !isset($attributes['alt'])) {
  184.  
  185.             // Копируем title в alt
  186.             $attributes['alt'] = $attributes['title'];
  187.  
  188.         // Если есть alt но нет title
  189.         } else if (isset($attributes['alt']) and !isset($attributes['title'])) {
  190.  
  191.             // Копируем alt в title
  192.             $attributes['title'] = $attributes['alt'];
  193.         }
  194.  
  195.         // Определяем разрешения использовать размеры
  196.         $width = $height = true;
  197.  
  198.         // Удадяем пиксели их щирины
  199.         if (isset($attributes['width'])) {
  200.             $attributes['width'] = str_replace('px', '', $attributes['width']);
  201.         }
  202.  
  203.         // Убираем пиксели из высоты
  204.         if (isset($attributes['height'])) {
  205.             $attributes['height'] = str_replace('px', '', $attributes['height']);
  206.         }
  207.  
  208.         // Если задана ширина, но нет высоты
  209.         if (isset($attributes['width']) and !isset($attributes['height'])) {
  210.  
  211.             // Если ширина в процентах
  212.             if (!is_numeric($attributes['width'])) {
  213.  
  214.                 // Отключаем использование высоты
  215.                 $height = false;
  216.  
  217.             // Иначе
  218.             } else if ($this->entity and $this->entity->width()) {
  219.  
  220.                 // Рассчитываем высоту по ширине
  221.                 $attributes['height'] = round($this->entity->height() * ((int) $attributes['width'] / $this->entity->width()));
  222.             }
  223.  
  224.             // Иначе если задана
  225.         } else if(isset($attributes['height']) and !isset($attributes['width'])) {
  226.  
  227.             // Если ширина в процентах
  228.             if (!is_numeric($attributes['height'])) {
  229.  
  230.                 // Отключаем использование ширины
  231.                 $width = false;
  232.  
  233.                 // Иначе
  234.             } else if($this->entity and $this->entity->height()) {
  235.  
  236.                 // Рассчитываем ширину по высоте
  237.                 $attributes['width'] = round($this->entity->width() * ((int) $attributes['height'] / $this->entity->height()));
  238.             }
  239.         }
  240.  
  241.         // Если задана сущность
  242.         if ($this->entity) {
  243.  
  244.             // Не задана ширина и разрешено применять ширину
  245.             if (!isset($attributes['width']) and $width) {
  246.  
  247.                 // Задаем ширину
  248.                 $attributes['width'] = $this->entity->width();
  249.             }
  250.  
  251.             // И разрешего применять высоту
  252.             if (!isset($attributes['height']) and $height) {
  253.  
  254.                 // Задаем высоту
  255.                 $attributes['height'] = $this->entity->height();
  256.             }
  257.         }
  258.  
  259.         // Тут сохраним результат
  260.         $result = [];
  261.  
  262.         // Проходим по атрибутам
  263.         foreach ($attributes as $attribute => $value) {
  264.  
  265.             // Добавляем к результату атрибут и значение если оно есть
  266.             $result[] = $this->escape($attribute) . ($value ? ('="' . $this->escape($value) . '"') : '');
  267.         }
  268.  
  269.         // Возвращаем результат
  270.         return $result;
  271.     }
  272.  
  273.     /**
  274.      * Преобразует специальные символы в HTML-сущности
  275.      *
  276.      * @param string $content
  277.      * @return string
  278.      */
  279.     protected function escape(string $content)
  280.     {
  281.         return htmlspecialchars($content);
  282.     }
  283.  
  284.     /**
  285.      * Преобразование в строку
  286.      *
  287.      * @return string
  288.      */
  289.     public function __toString()
  290.     {
  291.         // Делаем тэг alt с атрибутами
  292.         return '<img ' . implode(' ', $this->attrs()) . ' />';
  293.     }
  294. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement