MiconDiscoveryManager.php in Micon 2.x
File
src/MiconDiscoveryManager.php
View source
<?php
namespace Drupal\micon;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
use Drupal\Core\Plugin\Discovery\YamlDiscovery;
class MiconDiscoveryManager extends DefaultPluginManager {
protected $alterHook = 'micon_icons';
protected $defaults = [
'text' => '',
'regex' => '',
'icon' => '',
'weight' => 0,
];
protected $themeHandler;
public function __construct(ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler, CacheBackendInterface $cache_backend) {
$this->moduleHandler = $module_handler;
$this->themeHandler = $theme_handler;
$this
->setCacheBackend($cache_backend, 'micon.discovery', [
'micon.discovery',
]);
}
public function getDefinitionMatch($string) {
$definitions = $this
->getDefinitions();
$icon_id = NULL;
foreach ($definitions as $definition) {
if ($definition['text'] && $definition['text'] == $string) {
$icon_id = $definition['icon'];
break;
}
}
if (!$icon_id) {
foreach ($definitions as $definition) {
if ($definition['regex'] && preg_match('!' . $definition['regex'] . '!', $string)) {
$icon_id = $definition['icon'];
break;
}
}
}
return $icon_id;
}
protected function getDiscovery() {
if (!isset($this->discovery)) {
$this->discovery = new YamlDiscovery('micon.icons', $this->moduleHandler
->getModuleDirectories() + $this->themeHandler
->getThemeDirectories());
$this->discovery = new ContainerDerivativeDiscoveryDecorator($this->discovery);
}
return $this->discovery;
}
protected function providerExists($provider) {
return $this->moduleHandler
->moduleExists($provider) || $this->themeHandler
->themeExists($provider);
}
public function processDefinition(&$definition, $plugin_id) {
parent::processDefinition($definition, $plugin_id);
if (empty($definition['id'])) {
throw new PluginException(sprintf('Plugin (%s) definition must include "id".', $plugin_id));
}
if (empty($definition['icon'])) {
throw new PluginException(sprintf('Plugin (%s) definition must include "icon".', $plugin_id));
}
if (empty($definition['text']) && empty($definition['regex'])) {
throw new PluginException(sprintf('Plugin (%s) definition must include "text" or "regex".', $plugin_id));
}
}
}