/administrator/components/com_widgetkit/vendor/yootheme/framework/src/View/Asset/Filter/CssImageBase64Filter.php

https://gitlab.com/vnsoftdev/amms · PHP · 62 lines · 35 code · 11 blank · 16 comment · 5 complexity · 53b042790b51bf9491e7ec02892684ed MD5 · raw file

  1. <?php
  2. namespace YOOtheme\Framework\View\Asset\Filter;
  3. use YOOtheme\Framework\Routing\Request;
  4. use YOOtheme\Framework\View\Asset\AssetInterface;
  5. class CssImageBase64Filter implements FilterInterface
  6. {
  7. /**
  8. * @var string
  9. */
  10. protected $baseUrl;
  11. /**
  12. * @var string
  13. */
  14. protected $basePath;
  15. /**
  16. * Constructor.
  17. *
  18. * @param Request $request
  19. */
  20. public function __construct(Request $request)
  21. {
  22. $this->baseUrl = parse_url($request->getBaseUrl(), PHP_URL_PATH);
  23. $this->basePath = $request->getBasePath();
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function filterContent(AssetInterface $asset)
  29. {
  30. $images = array();
  31. $content = $asset->getContent();
  32. // get images and the related path
  33. if (preg_match_all('/url\(\s*[\'"]?([^\'"]+)[\'"]?\s*\)/Ui', $asset->getContent(), $matches)) {
  34. foreach ($matches[0] as $i => $url) {
  35. if (strpos($path = $matches[1][$i], $this->baseUrl) !== 0) {
  36. continue;
  37. }
  38. if ($path = realpath($this->basePath.'/'.ltrim(substr($path, strlen($this->baseUrl)), '/'))) {
  39. $images[$url] = $path;
  40. }
  41. }
  42. }
  43. // check if image exists and filesize < 10kb
  44. foreach ($images as $url => $path) {
  45. if (filesize($path) <= 10240 && preg_match('/\.(gif|png|jpg)$/i', $path, $extension)) {
  46. $content = str_replace($url, sprintf('url(data:image/%s;base64,%s)', str_replace('jpg', 'jpeg', strtolower($extension[1])), base64_encode(file_get_contents($path))), $content);
  47. }
  48. }
  49. $asset->setContent($content);
  50. }
  51. }