Craeckerffm
11/29/2016 - 11:57 AM

PHP, ProcessWire: SVG placement function

PHP, ProcessWire: SVG placement function

/**
 * placeSVG
 *
 * verson 1.0.4
 *
 * Insert svg file as svg markup or image tag
 *
 * @param  String    $filename              file relative to templates folder
 * @param  array     $option                
 *                     String markup        'img'|null, defines output
 *                     String path          alternate path
 *                     String url           alternate url
 * @return String                           output String
 */
function placeSVG(String $filename, $option = ['markup' => null]) {

  switch ($option['markup']) {
    
    case 'img':
      $baseUrl = isset($option['url']) ? $option['url'] : wire('config')->urls->templates;
      $baseUrl .= substr($baseUrl, -1) === '/' ? '' : '/';
      $filename = (strpos($filename, '/') === 0) ? substr($filename, 1) : $filename;
      
      $url = $baseUrl.$filename;
      return "<img src='$url'>";
      break;
    
    default:
      $basePath = isset($option['path']) ? $option['path'] : wire('config')->paths->templates;
      $basePath .= substr($basePath, -1) === '/' ? '' : '/';
      $filename = (strpos($filename, '/') === 0) ? substr($filename, 1) : $filename;
      
      $path = $basePath.$filename;
      $svgContent = file_get_contents($path);
      // strip doctype, xml definition, comments
      $svgOutput = preg_replace("/(\<\?xml.+?\?\>)|(\<\!DOCTYPE.+?\>)|(\<\!--.+?\-\-\>)/", '', $svgContent);
      return $svgOutput;
      break;
  }
}