View source
<?php
namespace Drupal\Tests\Core\Plugin;
use Drupal\Component\Plugin\CategorizingPluginManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\CategorizingPluginManagerTrait;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Tests\UnitTestCase;
class CategorizingPluginManagerTraitTest extends UnitTestCase {
protected $pluginManager;
protected function setUp() {
$module_handler = $this
->createMock('Drupal\\Core\\Extension\\ModuleHandlerInterface');
$module_handler
->expects($this
->any())
->method('getModuleList')
->willReturn([
'node' => [],
]);
$module_handler
->expects($this
->any())
->method('getName')
->with('node')
->willReturn('Node');
$this->pluginManager = new CategorizingPluginManager($module_handler);
$this->pluginManager
->setStringTranslation($this
->getStringTranslationStub());
}
public function testGetCategories() {
$this
->assertSame([
'fruits',
'vegetables',
], array_values($this->pluginManager
->getCategories()));
}
public function testGetSortedDefinitions() {
$sorted = $this->pluginManager
->getSortedDefinitions();
$this
->assertSame([
'apple',
'mango',
'cucumber',
], array_keys($sorted));
}
public function testGetGroupedDefinitions() {
$grouped = $this->pluginManager
->getGroupedDefinitions();
$this
->assertSame([
'fruits',
'vegetables',
], array_keys($grouped));
$this
->assertSame([
'apple',
'mango',
], array_keys($grouped['fruits']));
$this
->assertSame([
'cucumber',
], array_keys($grouped['vegetables']));
}
public function testProcessDefinitionCategory() {
$definition = [
'label' => 'some',
'provider' => 'core',
'category' => 'bag',
];
$this->pluginManager
->processDefinition($definition, 'some');
$this
->assertSame('bag', $definition['category']);
$definition = [
'label' => 'some',
'provider' => 'core',
];
$this->pluginManager
->processDefinition($definition, 'some');
$this
->assertSame('core', $definition['category']);
$definition = [
'label' => 'some',
'provider' => 'node',
];
$this->pluginManager
->processDefinition($definition, 'some');
$this
->assertSame('Node', $definition['category']);
}
}
class CategorizingPluginManager extends DefaultPluginManager implements CategorizingPluginManagerInterface {
use CategorizingPluginManagerTrait;
public function __construct(ModuleHandlerInterface $module_handler) {
$this->moduleHandler = $module_handler;
}
public function getDefinitions() {
return [
'cucumber' => [
'label' => 'cucumber',
'category' => 'vegetables',
],
'apple' => [
'label' => 'apple',
'category' => 'fruits',
],
'mango' => [
'label' => 'mango',
'category' => 'fruits',
],
];
}
public function processDefinition(&$definition, $plugin_id) {
parent::processDefinition($definition, $plugin_id);
$this
->processDefinitionCategory($definition);
}
}