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
->getMock('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(array_values($this->pluginManager
->getCategories()), [
'fruits',
'vegetables',
]);
}
public function testGetSortedDefinitions() {
$sorted = $this->pluginManager
->getSortedDefinitions();
$this
->assertSame(array_keys($sorted), [
'apple',
'mango',
'cucumber',
]);
}
public function testGetGroupedDefinitions() {
$grouped = $this->pluginManager
->getGroupedDefinitions();
$this
->assertSame(array_keys($grouped), [
'fruits',
'vegetables',
]);
$this
->assertSame(array_keys($grouped['fruits']), [
'apple',
'mango',
]);
$this
->assertSame(array_keys($grouped['vegetables']), [
'cucumber',
]);
}
public function testProcessDefinitionCategory() {
$definition = [
'label' => 'some',
'provider' => 'core',
'category' => 'bag',
];
$this->pluginManager
->processDefinition($definition, 'some');
$this
->assertSame($definition['category'], 'bag');
$definition = [
'label' => 'some',
'provider' => 'core',
];
$this->pluginManager
->processDefinition($definition, 'some');
$this
->assertSame($definition['category'], 'core');
$definition = [
'label' => 'some',
'provider' => 'node',
];
$this->pluginManager
->processDefinition($definition, 'some');
$this
->assertSame($definition['category'], 'Node');
}
}
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);
}
}