You are here

class ResponsiveImage in Image Lazyloader 8

Class ResponsiveImage.

Hierarchy

  • class \Drupal\lazyloader\ResponsiveImage implements \Drupal\lazyloader\IteratorAggregate, \Drupal\lazyloader\Countable

Expanded class hierarchy of ResponsiveImage

2 files declare their use of ResponsiveImage
lazyloader.module in ./lazyloader.module
Lazyloader Module.
ResponsiveImageTest.php in tests/src/Unit/ResponsiveImageTest.php

File

src/ResponsiveImage.php, line 8

Namespace

Drupal\lazyloader
View source
class ResponsiveImage implements \Countable, \IteratorAggregate {

  /**
   * The images.
   *
   * @var \stdClass[]
   */
  protected $images = [];

  /**
   * Creates a new ResponsiveImage instance.
   *
   * @param \stdClass[] $images
   *   The images.
   */
  public function __construct(array $images) {
    $this->images = $images;
  }

  /**
   * {@inheritdoc}
   */
  public function count() {
    return count($this->images);
  }

  /**
   * {@inheritdoc}
   */
  public function get($id) {
    return $this->images[$id];
  }

  /**
   * {@inheritdoc}
   */
  public function getIterator() {
    return new \ArrayIterator($this->images);
  }

  /**
   * Creates a responsive image instance from a string.
   *
   * @return $this
   */
  public static function parse($string) {
    $strings = array_map('trim', explode(',', $string));
    $images = array_map(function ($string) {
      $elements = explode(' ', $string);
      $object = new \stdClass();
      $object->uri = $elements[0];
      $object->density = NULL;
      $object->width = NULL;
      unset($elements[0]);
      foreach ($elements as $element) {
        if ($element[strlen($element) - 1] === 'w') {
          $object->width = substr($element, 0, -1);
        }
        if ($element[strlen($element) - 1] === 'x') {
          $object->density = substr($element, 0, -1);
        }
      }
      return $object;
    }, $strings);
    return new static($images);
  }

  /**
   * {@inheritdoc}
   */
  public function __toString() {
    return implode(', ', array_map(function ($element) {
      $string_elements = [
        $element->uri,
      ];
      if (!empty($element->width)) {
        $string_elements[] = $element->width . 'w';
      }
      if (!empty($element->density)) {
        $string_elements[] = $element->density . 'x';
      }
      return implode(' ', $string_elements);
    }, $this->images));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ResponsiveImage::$images protected property The images.
ResponsiveImage::count public function
ResponsiveImage::get public function
ResponsiveImage::getIterator public function
ResponsiveImage::parse public static function Creates a responsive image instance from a string.
ResponsiveImage::__construct public function Creates a new ResponsiveImage instance.
ResponsiveImage::__toString public function