bs_lib-8.x-1.0-alpha3/src/SvgTools.php

src/SvgTools.php
<?php

namespace Drupal\bs_lib;

/**
 * Defines a service with some handy SVG tools.
 */

class SvgTools {

  /**
   * Extracts width and height dimensions from an SVG content string.
   *
   * This function attempts to retrieve the width and height attributes from the
   * SVG content. If these attributes are not found, it falls back to extracting
   * the dimensions from the viewBox attribute. The extracted dimensions are
   * returned as an associative array with 'width' and 'height' keys.
   *
   * @param string $svg_content
   *   The SVG content to extract dimensions from.
   *
   * @return array|false
   *   An associative array containing 'width' and 'height' dimensions, or FALSE
   *   if width or height are not found.
   */
  public function getDimensions(string $svg_content)
  {
    $width = NULL;
    $height = NULL;

    // First try to get dimensions from width and height attribute.
    preg_match('/<svg[^>]*width=["\']?([^"\']+)["\']?[^>]*>/i', $svg_content, $widthMatches);
    if (!empty($widthMatches[1])) {
      $width = $widthMatches[1];
    }
    preg_match('/<svg[^>]*height=["\']?([^"\']+)["\']?[^>]*>/i', $svg_content, $heightMatches);
    if (!empty($heightMatches[1])) {
      $height = $heightMatches[1];
    }

    // If width or height attributes were not found, try to extract from
    // viewBox attribute.
    if (!$width || !$height) {
      preg_match('/<svg[^>]*viewBox=["\']?([^"\']+)["\']?[^>]*>/i', $svg_content, $viewBoxMatches);

      if (!empty($viewBoxMatches[1])) {
        $viewBoxValues = explode(' ', $viewBoxMatches[1]);
        if (count($viewBoxValues) >= 4) {
          $width = $viewBoxValues[2];
          $height = $viewBoxValues[3];
        }
      }
    }

    if (!empty($width) && !empty($height)) {
      return [
        'width' => $this->removeUnit($width),
        'height' => $this->removeUnit($height),
      ];
    }

    return FALSE;
  }

  /**
   * Removes units from a given value and returns the numeric representation.
   *
   * This method takes a string value as input, removes any non-numeric and
   * non-dot characters (excluding the dot to allow floating-point numbers),
   * and converts the resulting string to a float.
   *
   * @param string $value
   *   The input value, which may include units or be a numeric string.
   * @return float
   *   The numeric representation of the input value without units.
   *
   */
  protected function removeUnit($value) {
    // Remove non-numeric and non-dot characters from the value.
    $numericValue = preg_replace('/[^0-9.]/', '', $value);

    // Convert the numeric value to a float.
    return floatval($numericValue);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc