View source
<?php
namespace Drupal\micon;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Render\Markup;
use Drupal\Core\Render\RenderableInterface;
class MiconIcon implements MiconIconInterface, RenderableInterface {
protected $type;
protected $data;
protected $attributes;
public function __construct($type, array $data, array $attributes = []) {
$this->type = $type;
$this->data = $data;
$this
->setAttributes($attributes);
}
public function getType() {
return $this->type;
}
public function getPackageId() {
return $this->data['package_id'];
}
public function getPackageLabel() {
return $this->data['package_label'];
}
public function getPrefix() {
return $this->data['prefix'];
}
public function getTag() {
return $this->data['tag'];
}
public function getSelector() {
return $this
->getPrefix() . $this
->getTag();
}
public function getHex() {
return $this->type == 'font' ? '\\' . dechex($this->data['properties']['code']) : '';
}
public function getWrappingElement() {
return $this->type == 'image' ? 'svg' : 'i';
}
public function getChildren() {
$build = [];
if ($this->type == 'font') {
if (!empty($this->data['properties']['codes']) && count($this->data['properties']['codes'])) {
for ($i = 1; $i <= count($this->data['properties']['codes']); $i++) {
$build[]['#markup'] = '<span class="path' . $i . '"></span>';
}
}
}
if ($this->type == 'image') {
$build['#markup'] = Markup::create('<use xlink:href="' . $this->data['directory'] . '/symbol-defs.svg#' . $this
->getSelector() . '"></use>');
$build['#allowed_tags'] = [
'use',
'xlink',
];
}
return $build;
}
public function addClass($classes) {
$this->attributes
->addClass($classes);
return $this;
}
public function setAttributes(array $attributes) {
$this->attributes = new Attribute($attributes);
return $this;
}
public function setAttribute($attribute, $value) {
$this->attributes
->setAttribute($attribute, $value);
return $this;
}
public function toRenderable() {
return [
'#theme' => 'micon_icon',
'#icon' => $this,
'#attributes' => $this->attributes
->toArray(),
];
}
public function toMarkup() {
$elements = $this
->toRenderable();
return \Drupal::service('renderer')
->render($elements);
}
public function toJson() {
return json_encode(trim(preg_replace('/<!--(.|\\s)*?-->/', '', $this
->toMarkup()
->jsonSerialize())));
}
}