Skip to content

Instantly share code, notes, and snippets.

@vincentsmuda
Created September 12, 2018 19:59
Show Gist options
  • Save vincentsmuda/642f9bbe95c9ba65ac4369bf4013f479 to your computer and use it in GitHub Desktop.
Save vincentsmuda/642f9bbe95c9ba65ac4369bf4013f479 to your computer and use it in GitHub Desktop.
Statamic srcset modifier for content strings and general src manipulation
<?php
/**
*
* Srcset Modifier
* This modifier is meant to be used on objects with inaccessible srcsets.
*
* How to use:
* {{ content | srcsets:1440,1080,960,768,480,150 }}
* or <img src="{{ the_image | srcsets:1440,1080,960,768,480,150 }}">
*
*/
namespace Statamic\Addons\Srcsets;
use Statamic\Extend\Modifier;
use Statamic\API\Asset;
class SrcsetsModifier extends Modifier
{
/**
* Stores the content
* @var String
*/
private $content;
/**
* Default sizes to generate
* @var Array
*/
private $sizes = [
960,
768,
150
];
/**
* Modify a value
*
* @param mixed $value The value to be modified
* @param array $params Any parameters used in the modifier
* @param array $context Contextual values
* @return mixed
*/
public function index($content, $params, $context)
{
// Store the params as sizes
if(!empty($params)) {
$this->sizes = explode(',',$params[0]);
arsort($this->sizes);
};
// generate the srcsets
return $this->setContent($content)
->addSrcSets()
->getContent();
}
/**
* Stores the incoming content
* @return SrcsetsModifier
*/
private function setContent ($content) {
// Store the content
$this->content = $content;
// Make pipable
return $this;
}
/**
* Retreives the modified content
* @return String
*/
private function getContent () {
return $this->content;
}
/**
* Generates the srcsets
* @return SrcsetsModifier
*/
private function addSrcSets () {
// Find all the data srcs
if(preg_match('/^(\/|https?:\/\/)/', $this->content))
$img_urls = [0,[$this->content]];
else preg_match_all(
'/<img[^>]+?src="([^"]+)/',
$this->content,
$img_urls
);
// if there were matched images, loop through them
if(!empty($img_urls[1])) foreach ($img_urls[1] as $url) {
// Get the image
$asset = Asset::wherePath(trim($url,'/'));
// Start the srcset out empty
$srcset = "";
// Loop through the sizes and add them
// to an srcset string
foreach ($this->sizes as $size_index => $size)
$srcset .= ($srcset ? ', ' : '')
. $asset->manipulate(['w' => $size])
. " {$size}w" ;
// generate the correct image
$this->content = str_replace(
"{$url}",
"{$url}\" srcset=\"{$srcset}",
$this->content
);
}
// Make the method pipable
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment