Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for converting pictures with src-sets #85

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion Image/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,24 @@ class Image
*/
private $url;

/**
* @var ?string
*/
private $srcSet = null;

/**
* @param string $path
* @param string $url
* @param ?string $srcSet
*/
public function __construct(
string $path,
string $url
string $url,
?string $srcSet = null
) {
$this->path = $path;
$this->url = $url;
$this->srcSet = $srcSet;
}

/**
Expand All @@ -42,6 +50,22 @@ public function getUrl(): string
return $this->url;
}

/**
* @return ?string
*/
public function getSrcSet(): ?string
{
return $this->srcSet;
}

/**
* @param ?string
*/
public function setSrcSet(?string $srcSet): void
{
$this->srcSet = $srcSet;
}

/**
* @return string
*/
Expand Down
4 changes: 2 additions & 2 deletions Image/ImageCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ public function __construct(
}

/**
* @param string $imageUrl
* @param string|array $imageUrl
* @return Image[]
*/
public function collect(string $imageUrl): array
public function collect($imageUrl): array
{
try {
$image = $this->imageFactory->createFromUrl($imageUrl);
Expand Down
30 changes: 24 additions & 6 deletions Image/ImageFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,35 @@ public function createFromPath(string $path): Image
}

/**
* @param string $url
* @param array|string $url
* @return Image
* @throws FileSystemException
*/
public function createFromUrl(string $url): Image
public function createFromUrl($url): Image
{
$urls = is_array($url) ? $url : [$url];
$baseUrl = $this->cleanUrl($urls[0] ?? '');
$srcSet = $this->getSrcSet($urls);
$path = $this->urlConvertor->getFilenameFromUrl($baseUrl);
return $this->objectManager->create(Image::class, ['path' => $path, 'url' => $baseUrl, 'srcSet' => $srcSet]);
}

private function cleanUrl(string $url): string
{
if (strpos($url, 'http') !== false) {
$url = explode('?', $url)[0];
return explode('?', $url)[0];
}

$path = $this->urlConvertor->getFilenameFromUrl($url);
return $this->objectManager->create(Image::class, ['path' => $path, 'url' => $url]);

return $url;
}

private function getSrcSet(array $urls): string
{
$srcSetPieces = [];
foreach ($urls as $key => $url) {
$srcSetPieces[] = $this->cleanUrl($url) . ($key !== 0 ? (' ' . $key) : '');
}

return implode(',', $srcSetPieces);
}
}
20 changes: 20 additions & 0 deletions Test/Unit/Image/ImageFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ public function testCreateFromUrl()
$this->assertEquals('/foo/bar.jpg', $image->getUrl());
}

public function testCreateFromUrlWithMultipleUrls()
{
$urlConvertor = $this->getUrlConvertor();
$urlConvertor->method('getFilenameFromUrl')->willReturn('/tmp/pub/foo/bar.jpg');
$urlConvertor->method('getUrlFromFilename')->willReturn('/foo/bar.jpg');
$objectManager = $this->getObjectManager();
$objectManager->method('create')->willReturn(
new Image('/tmp/pub/foo/bar.jpg', '/foo/bar.jpg', '/foo/bar.jpg,/baz/qux.jpg 500w')
);

// @phpstan-ignore-next-line
$imageFactory = new ImageFactory($objectManager, $urlConvertor);
$image = $imageFactory->createFromUrl(['/foo/bar.jpg', '500w' => '/baz/qux.jpg']);

$this->assertInstanceOf(Image::class, $image);
$this->assertEquals('/tmp/pub/foo/bar.jpg', $image->getPath());
$this->assertEquals('/foo/bar.jpg', $image->getUrl());
$this->assertEquals('/foo/bar.jpg,/baz/qux.jpg 500w', $image->getSrcSet());
}

private function getObjectManager(): MockObject
{
return $this->getMockBuilder(ObjectManagerInterface::class)
Expand Down
6 changes: 6 additions & 0 deletions Test/Unit/Image/ImageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ public function testGetUrl()
$this->assertEquals('/media/foobar.jpg', $image->getUrl());
}

public function testGetSrcSet()
{
$image = new Image('/tmp/pub/foobar.jpg', '/media/foobar.jpg', '/foo/bar.jpg,/baz/qux.jpg 500w');
$this->assertEquals('/foo/bar.jpg,/baz/qux.jpg 500w', $image->getSrcSet());
}

public function testGetMimetype()
{
$image = new Image('/tmp/pub/foobar.gif', 'foobar.gif');
Expand Down
39 changes: 30 additions & 9 deletions Util/HtmlReplacer.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private function getImageHtmlFromImage(DOMElement $image, string $html): string
return '';
}

$regex = '/<img '.self::MARKER_CODE.'="'.$imageMarker.'"([^>"]*)(?:"[^"]*"[^>"]*)*>/';
$regex = '/<img '.self::MARKER_CODE.'="'.$imageMarker.'"([^\>]+)>/';
if (!preg_match($regex, $html, $imageHtmlMatch)) {
return '';
}
Expand All @@ -136,15 +136,35 @@ private function getPictureHtmlFromImage(DOMElement $image, string $html): strin
if (!$this->isAllowedByParentNode($image)) {
return '';
}

$imageSrcSet = $image->getAttribute('srcset');
if ($imageSrcSet) {
$srcSetImages = explode(',', $imageSrcSet);
$imageUrls = [];
foreach ($srcSetImages as $srcSetImage) {
$pieces = explode(' ', trim($srcSetImage));
if (isset($pieces[1])) {
$descriptor = $pieces[1];
$imageUrls[$descriptor] = $pieces[0];
} else {
$descriptor = 0;
$imageUrl = $imageUrls[$descriptor] = $pieces[0];
}
}
$images = $this->imageCollector->collect($imageUrls);
if (!count($images) > 0) {
return '';
}
} else {
$imageUrl = $this->getImageUrlFromElement($image);
if (!$this->isAllowedByImageUrl($imageUrl)) {
return '';
}

$imageUrl = $this->getImageUrlFromElement($image);
if (!$this->isAllowedByImageUrl($imageUrl)) {
return '';
}

$images = $this->imageCollector->collect($imageUrl);
if (!count($images) > 0) {
return '';
$images = $this->imageCollector->collect($imageUrl);
if (!count($images) > 0) {
return '';
}
}

$imageHtml = $this->getImageHtmlFromImage($image, $html);
Expand Down Expand Up @@ -271,6 +291,7 @@ private function replaceInlineCssBackgroundImages(string $html): string
private function getImageUrlFromElement(DOMElement $image): string
{
$attributes = $this->getAllowedSrcAttributes();

$imageUrl = '';
foreach ($attributes as $attribute) {
$imageUrl = $image->getAttribute($attribute);
Expand Down
23 changes: 22 additions & 1 deletion view/frontend/templates/picture.phtml
Original file line number Diff line number Diff line change
@@ -1 +1,22 @@
<?php declare(strict_types=1); use Yireo\NextGenImages\Block\Picture; /** @var $block Picture */ $width = ($block->getWidth()) ? ' width="'.$block->getWidth().'"' : ''; $height = ($block->getHeight()) ? ' height="'.$block->getHeight().'"' : ''; $class = ($block->getClass()) ? ' class="'.$block->getClass().'"' : ''; $lazyLoading = ($block->getLazyLoading()) ? ' loading="lazy" ' : ''; $originalTag = trim($block->getOriginalTag()); $originalTag = preg_replace('/(\/?)>$/', $lazyLoading.'\1>', $originalTag); $originalImage = $block->getOriginalImage(); $originalImageType = $block->getOriginalImageType(); $srcAttribute = $block->getSrcAttribute() ?? 'src'; $srcSetAttribute = $srcAttribute.'set'; ?> <?php if ($block->getDebug()): ?> <!-- <?= /* @noEscape */ $block->getOriginalTag() ?> --><?php endif; ?> <picture<?= /* @noEscape */ $class ?>><?php if ($block->getDebug()): ?> <!-- <?= $block->getOriginalAttributesAsString() ?> --><?php endif; ?> <?php foreach ($block->getImages() as $image): ?> <source type="<?= /* @noEscape */ $image->getMimeType() ?>" <?= /* @noEscape */ $srcSetAttribute ?>="<?= /* @noEscape */ $image->getUrl() ?>" <?= /* @noEscape */ $block->getSourceAttributesAsString() ?> ><?php endforeach; ?> <?= /* @noEscape */ $originalTag ?></picture>
<?php declare(strict_types=1);
use Yireo\NextGenImages\Block\Picture;
/** @var $block Picture */
$width = ($block->getWidth()) ? ' width="'.$block->getWidth().'"' : '';
$height = ($block->getHeight()) ? ' height="'.$block->getHeight().'"' : '';
$class = ($block->getClass()) ? ' class="'.$block->getClass().'"' : '';
$lazyLoading = ($block->getLazyLoading()) ? ' loading="lazy" ' : '';
$originalTag = trim($block->getOriginalTag());
$originalTag = preg_replace('/(\/?)>$/', $lazyLoading.'\1>', $originalTag);
$originalImage = $block->getOriginalImage();
$originalImageType = $block->getOriginalImageType();
$srcAttribute = $block->getSrcAttribute() ?? 'src';
$srcSetAttribute = $srcAttribute.'set'; ?>

<?php if ($block->getDebug()): ?> <!-- <?= /* @noEscape */ $block->getOriginalTag() ?> --><?php endif; ?>
<picture<?= /* @noEscape */ $class ?>>
<?php if ($block->getDebug()): ?> <!-- <?= $block->getOriginalAttributesAsString() ?> --><?php endif; ?>
<?php foreach ($block->getImages() as $image): ?>
<source type="<?= /* @noEscape */ $image->getMimeType() ?>" <?= /* @noEscape */ $srcSetAttribute ?>="<?= /* @noEscape */ $image->getSrcSet() ?: $image->getUrl() ?>" <?= /* @noEscape */ $block->getSourceAttributesAsString() ?> >
<?php endforeach; ?>
<?= /* @noEscape */ $originalTag ?>
</picture>