imgsrcset.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * ImgSrcset Plugin
  4. *
  5. * PHP version 7
  6. *
  7. * @category Extensions
  8. * @package Grav
  9. * @subpackage ImgSrcset
  10. * @author Ole Vik <git@olevik.net>
  11. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  12. * @link https://github.com/OleVik/grav-plugin-imgsrcset
  13. */
  14. namespace Grav\Plugin;
  15. use Grav\Common\Data;
  16. use Grav\Common\Plugin;
  17. use Grav\Common\Grav;
  18. use Grav\Common\Page\Page;
  19. use RocketTheme\Toolbox\Event\Event;
  20. use PHPHtmlParser\Dom;
  21. /**
  22. * Adds a srcset-attribute to img-elements to allow for responsive images in Markdown
  23. *
  24. * Class ImgSrcsetPlugin
  25. *
  26. * @category Extensions
  27. * @package Grav\Plugin
  28. * @author Ole Vik <git@olevik.net>
  29. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  30. * @link https://github.com/OleVik/grav-plugin-imgsrcset
  31. */
  32. class ImgSrcsetPlugin extends Plugin
  33. {
  34. /**
  35. * Register events with Grav
  36. *
  37. * @return array
  38. */
  39. public static function getSubscribedEvents()
  40. {
  41. return [
  42. 'onPageContentProcessed' => ['onPageContentProcessed', 0]
  43. ];
  44. }
  45. /**
  46. * Iterates over images in page content and rewrites paths
  47. *
  48. * @return void
  49. */
  50. public function onPageContentProcessed()
  51. {
  52. if ($this->isAdmin()) {
  53. return;
  54. }
  55. $config = (array) $this->config->get('plugins.imgsrcset');
  56. $page = $this->grav['page'];
  57. $config = $this->mergeConfig($page);
  58. if ($config['enabled']) {
  59. include __DIR__ . '/vendor/autoload.php';
  60. $dom = new Dom;
  61. $dom->load($page->getRawContent());
  62. $images = $dom->find('img');
  63. $widths = $config['widths'];
  64. foreach ($images as $image) {
  65. $file = pathinfo($image->getAttribute('src'));
  66. $dirname = $file['dirname'];
  67. $filename = $file['filename'];
  68. $extension = $file['extension'];
  69. $srcsets = '';
  70. foreach ($widths as $width) {
  71. $srcsets .= $dirname.'/'.$filename.'-'.$width.'.'.$extension.' '.$width.'w, ';
  72. }
  73. $srcsets = rtrim($srcsets, ", ");
  74. $image->setAttribute('srcset', $srcsets);
  75. $image->setAttribute('sizes', $config['sizes']);
  76. }
  77. $page->setRawContent($dom->outerHtml);
  78. }
  79. }
  80. }