Pathauto and dependencies

This commit is contained in:
Rob Davies 2017-05-22 15:12:47 +01:00
parent 4b1a293d57
commit 24ffcb956b
257 changed files with 29510 additions and 0 deletions

View file

@ -0,0 +1,18 @@
ctools_wizard_test.ctools_wizard_test_config_entity.*:
type: config_entity
label: 'Example config entity'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
uuid:
type: string
one:
type: string
label: 'The first piece of information'
two:
type: string
label: 'The second piece of information'

View file

@ -0,0 +1,12 @@
name: Chaos Wizard Test
type: module
description: 'Provides testing for ctools wizard'
package: Testing
# version: 3.x
# core: 8.x
# Information added by Drupal.org packaging script on 2017-04-28
version: '8.x-3.0'
core: '8.x'
project: 'ctools'
datestamp: 1493401747

View file

@ -0,0 +1,6 @@
entity.ctools_wizard_test_config_entity.add_form:
route_name: 'entity.ctools_wizard_test_config_entity.add_form'
title: 'Add Example config entity'
appears_on:
- entity.ctools_wizard_test_config_entity.collection

View file

@ -0,0 +1,7 @@
# Example config entity menu items definition
entity.ctools_wizard_test_config_entity.collection:
title: 'Example config entity'
route_name: entity.ctools_wizard_test_config_entity.collection
description: 'List Example config entity'
parent: system.admin_structure

View file

@ -0,0 +1,82 @@
ctools.wizard.test:
path: '/ctools/wizard'
defaults:
_wizard: '\Drupal\ctools_wizard_test\Wizard\WizardTest'
_title: 'Wizard Test'
tempstore_id: 'ctools.wizard.test'
machine_name: 'WizardTest'
requirements:
_access: 'TRUE'
ctools.wizard.test.step:
path: '/ctools/wizard/{step}'
defaults:
_wizard: '\Drupal\ctools_wizard_test\Wizard\WizardTest'
_title: 'Wizard Test'
tempstore_id: 'ctools.wizard.test'
machine_name: 'WizardTest'
requirements:
_access: 'TRUE'
# ExampleConfigEntity routing definition
entity.ctools_wizard_test_config_entity.collection:
path: '/admin/structure/ctools_wizard_test_config_entity'
defaults:
_entity_list: 'ctools_wizard_test_config_entity'
_title: 'Example config entity'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE
entity.ctools_wizard_test_config_entity.add_form:
path: '/admin/structure/ctools_wizard_test_config_entity/add'
defaults:
_entity_wizard: 'ctools_wizard_test_config_entity.add'
_title: 'Add Example config entity'
tempstore_id: 'ctools_wizard_test.config_entity'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE
entity.ctools_wizard_test_config_entity.add_step_form:
path: '/admin/structure/ctools_wizard_test_config_entity/add/{machine_name}/{step}'
defaults:
_entity_wizard: 'ctools_wizard_test_config_entity.add'
_title: 'Add Example config entity'
tempstore_id: 'ctools_wizard_test.config_entity'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE
entity.ctools_wizard_test_config_entity.edit_form:
path: '/admin/structure/ctools_wizard_test_config_entity/{machine_name}/{step}'
defaults:
_entity_wizard: 'ctools_wizard_test_config_entity.edit'
_title: 'Edit Example config entity'
tempstore_id: 'ctools_wizard_test.config_entity'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE
entity.ctools_wizard_test_config_entity.external_form:
path: '/admin/structure/ctools_wizard_test_config_entity/{machine_name}/external'
defaults:
_title: 'Edit Example config entity'
_form: '\Drupal\ctools_wizard_test\Form\ExampleConfigEntityExternalForm'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE
entity.ctools_wizard_test_config_entity.delete_form:
path: '/admin/structure/ctools_wizard_test_config_entity/{ctools_wizard_test_config_entity}/delete'
defaults:
_entity_form: 'ctools_wizard_test_config_entity.delete'
_title: 'Delete Example config entity'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE

View file

@ -0,0 +1,83 @@
<?php
namespace Drupal\ctools_wizard_test\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\ctools_wizard_test\ExampleConfigEntityInterface;
/**
* Defines the Example config entity entity.
*
* @ConfigEntityType(
* id = "ctools_wizard_test_config_entity",
* label = @Translation("Example config entity"),
* handlers = {
* "list_builder" = "Drupal\ctools_wizard_test\ExampleConfigEntityListBuilder",
* "form" = {
* "delete" = "Drupal\ctools_wizard_test\Form\ExampleConfigEntityDeleteForm"
* },
* "wizard" = {
* "add" = "Drupal\ctools_wizard_test\Wizard\EntityAddWizardTest",
* "edit" = "Drupal\ctools_wizard_test\Wizard\EntityEditWizardTest"
* }
* },
* config_prefix = "ctools_wizard_test_config_entity",
* admin_permission = "administer site configuration",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* "uuid" = "uuid"
* },
* links = {
* "canonical" = "/admin/structure/ctools_wizard_test_config_entity/{ctools_wizard_test_config_entity}",
* "edit-form" = "/admin/structure/ctools_wizard_test_config_entity/{machine_name}/{step}",
* "delete-form" = "/admin/structure/ctools_wizard_test_config_entity/{ctools_wizard_test_config_entity}/delete",
* "collection" = "/admin/structure/ctools_wizard_test_config_entity"
* }
* )
*/
class ExampleConfigEntity extends ConfigEntityBase implements ExampleConfigEntityInterface {
/**
* The Example config entity ID.
*
* @var string
*/
protected $id;
/**
* The Example config entity label.
*
* @var string
*/
protected $label;
/**
* The first piece of information.
*
* @var string
*/
protected $one;
/**
* The second piece of information.
*
* @var string
*/
protected $two;
/**
* @inheritDoc
*/
public function getOne() {
return $this->one;
}
/**
* @inheritDoc
*/
public function getTwo() {
return $this->two;
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Drupal\ctools_wizard_test;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Provides an interface for defining Example config entity entities.
*/
interface ExampleConfigEntityInterface extends ConfigEntityInterface {
/**
* Get first piece of information.
*
* @return string
*/
public function getOne();
/**
* Get second piece of information;
*
* @return string
*/
public function getTwo();
}

View file

@ -0,0 +1,49 @@
<?php
namespace Drupal\ctools_wizard_test;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides a listing of Example config entity entities.
*/
class ExampleConfigEntityListBuilder extends ConfigEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Example config entity');
$header['id'] = $this->t('Machine name');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row['label'] = $this->getLabel($entity);
$row['id'] = $entity->id();
// You probably want a few more properties here...
return $row + parent::buildRow($entity);
}
/**
* @inheritDoc
*/
public function getOperations(EntityInterface $entity) {
$operations = parent::getOperations($entity);
if (!empty($operations['edit'])) {
/** @var \Drupal\Core\Url $edit */
$edit = $operations['edit']['url'];
$edit->setRouteParameters([
'machine_name' => $entity->id(),
'step' => 'general',
]);
}
return $operations;
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Builds the form to delete Example config entity entities.
*/
class ExampleConfigEntityDeleteForm extends EntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete %name?', array('%name' => $this->entity->label()));
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('entity.ctools_wizard_test_config_entity.collection');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->entity->delete();
drupal_set_message(
$this->t('content @type: deleted @label.',
[
'@type' => $this->entity->bundle(),
'@label' => $this->entity->label()
]
)
);
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Simple wizard step form.
*/
class ExampleConfigEntityExistingForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ctools_wizard_test_config_entity_existing_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['existing'] = array(
'#markup' => '<p>This step only shows if the entity is already existing!</p>',
);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Do nothing!
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\SharedTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ExampleConfigEntityExternalForm extends FormBase {
/**
* Tempstore factory.
*
* @var \Drupal\user\SharedTempStoreFactory
*/
protected $tempstore;
/**
* Constructs a new ExampleConfigEntityExternalForm.
*
* @param \Drupal\ctools_wizard_test\Form\SharedTempStoreFactory $tempstore
*/
function __construct(SharedTempStoreFactory $tempstore) {
$this->tempstore = $tempstore;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('user.shared_tempstore'));
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ctools_wizard_test_example_config_entity_external_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $machine_name = '') {
$cached_values = $this->tempstore->get('ctools_wizard_test.config_entity')->get($machine_name);
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
$form['blah'] = [
'#markup' => 'Value from one: ' . $config_entity->getOne(),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Don't do anything.
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class ExampleConfigEntityForm.
*/
class ExampleConfigEntityGeneralForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ctools_wizard_test_config_entity_general_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
// The label and id will be added by the EntityFormWizardBase.
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
$config_entity->set('id', $form_state->getValue('id'));
$config_entity->set('label', $form_state->getValue('label'));
}
}

View file

@ -0,0 +1,62 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Simple wizard step form.
*/
class ExampleConfigEntityOneForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ctools_wizard_test_config_entity_one_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
$form['one'] = [
'#title' => $this->t('One'),
'#type' => 'textfield',
'#default_value' => $config_entity->getOne() ?: '',
];
$form['external'] = [
'#type' => 'link',
'#title' => $this->t('Show on dialog'),
'#url' => new Url('entity.ctools_wizard_test_config_entity.external_form', [
'machine_name' => $config_entity->id(),
]),
'#attributes' => [
'class' => 'use-ajax',
'data-dialog-type' => 'modal',
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
$config_entity->set('one', $form_state->getValue('one'));
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Simple wizard step form.
*/
class ExampleConfigEntityTwoForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ctools_wizard_test_config_entity_two_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
$form['two'] = array(
'#title' => $this->t('Two'),
'#type' => 'textfield',
'#default_value' => $config_entity->getTwo() ?: '',
);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
$config_entity->set('two', $form_state->getValue('two'));
}
}

View file

@ -0,0 +1,71 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Simple wizard step form.
*/
class OneForm extends FormBase {
/**
* Returns a unique string identifying the form.
*
* @return string
* The unique string identifying the form.
*/
public function getFormId() {
return 'ctools_wizard_test_one_form';
}
/**
* Form constructor.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return array
* The form structure.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
$form['one'] = [
'#title' => $this->t('One'),
'#type' => 'textfield',
'#default_value' => !empty($cached_values['one']) ? $cached_values['one'] : '',
];
$form['dynamic'] = [
'#title' => $this->t('Dynamic value'),
'#type' => 'item',
'#markup' => !empty($cached_values['dynamic']) ? $cached_values['dynamic'] : '',
];
return $form;
}
/**
* Form submission handler.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$keys = array(
'one',
);
$cached_values = $form_state->getTemporaryValue('wizard');
foreach ($keys as $key) {
$cached_values[$key] = $form_state->getValue($key);
}
$form_state->setTemporaryValue('wizard', $cached_values);
drupal_set_message($this->t('Dynamic value submitted: @value', ['@value' => $cached_values['dynamic']]));;
}
}

View file

@ -0,0 +1,69 @@
<?php
namespace Drupal\ctools_wizard_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Simple wizard step form.
*/
class TwoForm extends FormBase {
/**
* Returns a unique string identifying the form.
*
* @return string
* The unique string identifying the form.
*/
public function getFormId() {
return 'ctools_wizard_test_two_form';
}
/**
* Form constructor.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return array
* The form structure.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
$form['two'] = [
'#title' => $this->t('Two'),
'#type' => 'textfield',
'#default_value' => !empty($cached_values['two']) ? $cached_values['two'] : '',
];
$form['dynamic'] = [
'#title' => $this->t('Dynamic value'),
'#type' => 'item',
'#markup' => !empty($cached_values['dynamic']) ? $cached_values['dynamic'] : '',
];
return $form;
}
/**
* Form submission handler.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$keys = array(
'two',
);
$cached_values = $form_state->getTemporaryValue('wizard');
foreach ($keys as $key) {
$cached_values[$key] = $form_state->getValue($key);
}
$form_state->setTemporaryValue('wizard', $cached_values);
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace Drupal\ctools_wizard_test\Wizard;
class EntityAddWizardTest extends EntityEditWizardTest {
/**
* {@inheritdoc}
*/
public function getRouteName() {
return 'entity.ctools_wizard_test_config_entity.add_step_form';
}
}

View file

@ -0,0 +1,71 @@
<?php
namespace Drupal\ctools_wizard_test\Wizard;
use Drupal\ctools\Wizard\EntityFormWizardBase;
class EntityEditWizardTest extends EntityFormWizardBase {
/**
* {@inheritdoc}
*/
public function getWizardLabel() {
return $this->t('Example entity');
}
/**
* {@inheritdoc}
*/
public function getMachineLabel() {
return $this->t('Label');
}
/**
* {@inheritdoc}
*/
public function getEntityType() {
return 'ctools_wizard_test_config_entity';
}
/**
* {@inheritdoc}
*/
public function exists() {
return '\Drupal\ctools_wizard_test\Entity\ExampleConfigEntity::load';
}
/**
* {@inheritdoc}
*/
public function getOperations($cached_values) {
/** @var $page \Drupal\ctools_wizard_test\Entity\ExampleConfigEntity */
$config_entity = $cached_values['ctools_wizard_test_config_entity'];
$steps = [
'general' => [
'form' => 'Drupal\ctools_wizard_test\Form\ExampleConfigEntityGeneralForm',
'title' => $this->t('General'),
],
'one' => [
'form' => 'Drupal\ctools_wizard_test\Form\ExampleConfigEntityOneForm',
'title' => $this->t('Form One'),
],
'two' => [
'form' => 'Drupal\ctools_wizard_test\Form\ExampleConfigEntityTwoForm',
'title' => $this->t('Form Two'),
],
];
// To test that we can get the config entity and add/remove steps
// based on it's values, we'll add a special step only when the entity
// is pre-existing.
if (!empty($config_entity) && !$config_entity->isNew()) {
$steps['existing'] = [
'form' => 'Drupal\ctools_wizard_test\Form\ExampleConfigEntityExistingForm',
'title' => $this->t('Existing entity'),
];
}
return $steps;
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace Drupal\ctools_wizard_test\Wizard;
use Drupal\Core\Form\FormStateInterface;
use Drupal\ctools\Wizard\FormWizardBase;
class WizardTest extends FormWizardBase {
/**
* {@inheritdoc}
*/
public function getWizardLabel() {
return $this->t('Wizard Information');
}
/**
* {@inheritdoc}
*/
public function getMachineLabel() {
return $this->t('Wizard Test Name');
}
/**
* {@inheritdoc}
*/
public function getOperations($cached_values) {
return array(
'one' => [
'form' => 'Drupal\ctools_wizard_test\Form\OneForm',
'title' => $this->t('Form One'),
'values' => ['dynamic' => 'Xylophone'],
'validate' => ['::stepOneValidate'],
'submit' => ['::stepOneSubmit'],
],
'two' => [
'form' => 'Drupal\ctools_wizard_test\Form\TwoForm',
'title' => $this->t('Form Two'),
'values' => ['dynamic' => 'Zebra'],
],
);
}
/**
* Validation callback for the first step.
*/
public function stepOneValidate($form, FormStateInterface $form_state) {
if ($form_state->getValue('one') == 'wrong') {
$form_state->setErrorByName('one', $this->t('Cannot set the value to "wrong".'));
}
}
/**
* Submission callback for the first step.
*/
public function stepOneSubmit($form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
if ($form_state->getValue('one') == 'magic') {
$cached_values['one'] = 'Abraham';
}
$form_state->setTemporaryValue('wizard', $cached_values);
}
/**
* {@inheritdoc}
*/
public function getRouteName() {
return 'ctools.wizard.test.step';
}
/**
* {@inheritdoc}
*/
public function finish(array &$form, FormStateInterface $form_state) {
$cached_values = $form_state->getTemporaryValue('wizard');
drupal_set_message($this->t('Value One: @one', ['@one' => $cached_values['one']]));
drupal_set_message($this->t('Value Two: @two', ['@two' => $cached_values['two']]));
parent::finish($form, $form_state);
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace Drupal\Tests\ctools\Kernel;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
/**
* @coversDefaultClass \Drupal\ctools\Plugin\RelationshipManagerInterface
* @group CTools
*/
class RelationshipManagerTest extends RelationshipsTestBase {
/**
* @covers ::getDefinitions
*/
public function testRelationshipConstraints() {
$definitions = $this->relationshipManager->getDefinitions();
$expected = [
'Bundle' => [
0 => "page",
1 => "foo"
]
];
$this->assertSame($expected, $definitions['typed_data_relationship:entity:node:body']['context']['base']->getConstraints());
// Check that typed data primitive labels are formatted properly.
$this->assertSame('Body from Page and Foo', (string) $definitions['typed_data_relationship:entity:node:body']['label']);
// Check that entity relationship labels are formatted properly.
$this->assertSame('Authored by Entity from Content', (string) $definitions['typed_data_entity_relationship:entity:node:uid']['label']);
// Check that language relationship labels are formatted properly.
$this->assertSame('Language Language from Content', (string) $definitions['typed_data_language_relationship:entity:node:langcode']['label']);
}
/**
* @covers ::getDefinitionsForContexts
*/
public function testRelationshipPluginAvailability() {
$context_definition = new ContextDefinition('entity:node');
$contexts = [
'node' => new Context($context_definition, $this->entities['node1']),
];
$definitions = $this->relationshipManager->getDefinitionsForContexts($contexts);
//$this->assertTrue(isset($definitions['typed_data_relationship:entity:node:body']));
$context_definition = new ContextDefinition('entity:node');
$contexts = [
'node' => new Context($context_definition, $this->entities['node2']),
];
$definitions = $this->relationshipManager->getDefinitionsForContexts($contexts);
$this->assertFalse(isset($definitions['typed_data_relationship:entity:node:body']));
$context_definition = new ContextDefinition('entity:node');
$contexts = [
'node' => new Context($context_definition, $this->entities['node3']),
];
$definitions = $this->relationshipManager->getDefinitionsForContexts($contexts);
//$this->assertTrue(isset($definitions['typed_data_relationship:entity:node:body']));
}
}

View file

@ -0,0 +1,96 @@
<?php
namespace Drupal\Tests\ctools\Kernel;
use Drupal\ctools\Testing\EntityCreationTrait;
use Drupal\KernelTests\KernelTestBase;
abstract class RelationshipsTestBase extends KernelTestBase {
use EntityCreationTrait;
/**
* @var \Drupal\ctools\Plugin\RelationshipManagerInterface
*/
protected $relationshipManager;
/**
* @var \Drupal\Core\Entity\EntityInterface[]
*/
protected $entities = [];
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'user',
'system',
'node',
'field',
'text',
'filter',
'ctools'
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', ['sequences', 'router']);
$this->installEntitySchema('user');
$this->installEntitySchema('node_type');
$this->installEntitySchema('node');
$this->installConfig('node');
$page = $this->createEntity('node_type', [
'type' => 'page',
'name' => 'Page'
]);
node_add_body_field($page);
$article = $this->createEntity('node_type', [
'type' => 'article',
'name' => 'Article'
]);
// Not adding the body field the articles so that we can perform a test.
$foo = $this->createEntity('node_type', [
'type' => 'foo',
'name' => 'Foo'
]);
node_add_body_field($foo);
$this->relationshipManager = $this->container->get('plugin.manager.ctools.relationship');
$user = $this->createEntity('user', [
'name' => 'test_user',
'password' => 'password',
'mail' => 'mail@test.com',
'status' => 1,
]);
$node1 = $this->createEntity('node', [
'title' => 'Node 1',
'type' => 'page',
'uid' => $user->id(),
'body' => 'This is a test',
]);
$node2 = $this->createEntity('node', [
'title' => 'Node 2',
'type' => 'article',
'uid' => $user->id()
]);
$node3 = $this->createEntity('node', [
'title' => 'Node 3',
'type' => 'foo',
'uid' => $user->id()
]);
$this->entities = [
'user' => $user,
'node1' => $node1,
'node2' => $node2,
'node3' => $node3,
];
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace Drupal\Tests\ctools\Kernel;
use Drupal\ctools\SerializableTempstore;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
/**
* Tests the serializable tempstore service.
*
* @group ctools
*/
class SerializableTempstoreTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['ctools', 'system', 'user'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', ['key_value_expire']);
}
/**
* Tests serializing a serializable temp store object.
*/
public function testSerializableTempStore() {
$store = $this->container
->get('ctools.serializable.tempstore.factory')
->get('foobar');
// Add an unserializable request to the request stack. If the tempstore
// didn't use DependencySerializationTrait, the exception would be thrown
// when we try to serialize the tempstore.
$request = $this->prophesize(Request::class);
$request->willImplement('\Serializable');
$request->serialize()->willThrow(new \LogicException('Not cool, bruh!'));
$this->container->get('request_stack')->push($request->reveal());
$this->assertInstanceOf(SerializableTempstore::class, $store);
/** @var SerializableTempstore $store */
$store = serialize($store);
$this->assertInternalType('string', $store);
$this->assertNotEmpty($store, 'The tempstore was serialized.');
$store = unserialize($store);
$this->assertInstanceOf(SerializableTempstore::class, $store, 'The tempstore was unserialized.');
$request_stack = $this->getObjectAttribute($store, 'requestStack');
$this->assertSame(
$this->container->get('request_stack'),
$request_stack,
'The request stack was pulled from the container during unserialization.'
);
$this->assertSame($request->reveal(), $request_stack->pop());
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\ctools\Kernel;
use Drupal\node\Entity\NodeType;
use Drupal\user\Entity\User;
/**
* @coversDefaultClass \Drupal\ctools\Plugin\Relationship\TypedDataEntityRelationship
* @group CTools
*/
class TypedDataEntityRelationshipPluginTest extends RelationshipsTestBase {
/**
* @covers ::getName
*/
public function testRelationshipName() {
/** @var \Drupal\ctools\Plugin\RelationshipInterface $nid_plugin */
$type_plugin = $this->relationshipManager->createInstance('typed_data_entity_relationship:entity:node:type');
$this->assertSame('type', $type_plugin->getName());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $uuid_plugin */
$uid_plugin = $this->relationshipManager->createInstance('typed_data_entity_relationship:entity:node:uid');
$this->assertSame('uid', $uid_plugin->getName());
}
/**
* @covers ::getRelationship
*/
public function testRelationship() {
/** @var \Drupal\ctools\Plugin\RelationshipInterface $type_plugin */
$type_plugin = $this->relationshipManager->createInstance('typed_data_entity_relationship:entity:node:type');
$type_plugin->setContextValue('base', $this->entities['node1']);
$relationship = $type_plugin->getRelationship();
$this->assertTrue($relationship->getContextValue() instanceof NodeType);
$this->assertSame('entity:node_type', $relationship->getContextDefinition()->getDataType());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $uid_plugin */
$uid_plugin = $this->relationshipManager->createInstance('typed_data_entity_relationship:entity:node:uid');
$uid_plugin->setContextValue('base', $this->entities['node3']);
$relationship = $uid_plugin->getRelationship();
$this->assertTrue($relationship->getContextValue() instanceof User);
$this->assertSame('entity:user', $relationship->getContextDefinition()->getDataType());
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Drupal\Tests\ctools\Kernel;
use Drupal\Core\Language\LanguageInterface;
/**
* @coversDefaultClass \Drupal\ctools\Plugin\Relationship\TypedDataEntityRelationship
* @group CTools
*/
class TypedDataLanguageRelationshipPluginTest extends RelationshipsTestBase {
/**
* @covers ::getName
*/
public function testRelationshipName() {
/** @var \Drupal\ctools\Plugin\RelationshipInterface $langcode_plugin */
$langcode_plugin = $this->relationshipManager->createInstance('typed_data_language_relationship:entity:node:langcode');
$this->assertSame('langcode', $langcode_plugin->getName());
}
/**
* @covers ::getRelationship
*
* @todo expand to include a new language.
*/
public function testRelationship() {
/** @var \Drupal\ctools\Plugin\RelationshipInterface $langcode_plugin */
$langcode_plugin = $this->relationshipManager->createInstance('typed_data_language_relationship:entity:node:langcode');
$langcode_plugin->setContextValue('base', $this->entities['node1']);
$relationship = $langcode_plugin->getRelationship();
$this->assertTrue($relationship->getContextValue() instanceof LanguageInterface);
$this->assertSame('en', $relationship->getContextValue()->getId());
}
}

View file

@ -0,0 +1,103 @@
<?php
namespace Drupal\Tests\ctools\Kernel;
use Drupal\Core\Plugin\Context\ContextInterface;
/**
* @coversDefaultClass \Drupal\ctools\Plugin\Relationship\TypedDataRelationship
* @group CTools
*/
class TypedDataRelationshipPluginTest extends RelationshipsTestBase {
/**
* @covers ::getName
*/
public function testRelationshipName() {
/** @var \Drupal\ctools\Plugin\RelationshipInterface $nid_plugin */
$nid_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:nid');
$this->assertSame('nid', $nid_plugin->getName());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $uuid_plugin */
$uuid_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:uuid');
$this->assertSame('uuid', $uuid_plugin->getName());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $title_plugin */
$title_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:title');
$this->assertSame('title', $title_plugin->getName());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $body_plugin */
$body_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:body');
$this->assertSame('body', $body_plugin->getName());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $uid_plugin */
$uid_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:uid');
$this->assertSame('uid', $uid_plugin->getName());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $mail_plugin */
$mail_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:user:mail');
$this->assertSame('mail', $mail_plugin->getName());
}
/**
* @covers ::getRelationship
*/
public function testRelationship() {
/** @var \Drupal\ctools\Plugin\RelationshipInterface $nid_plugin */
$nid_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:nid');
$nid_plugin->setContextValue('base', $this->entities['node1']);
$relationship = $nid_plugin->getRelationship();
$this->assertTrue($relationship instanceof ContextInterface);
$this->assertTrue($relationship->getContextDefinition()->getDataType() == 'integer');
$this->assertTrue($relationship->hasContextValue());
$this->assertTrue($relationship->getContextValue() == $this->entities['node1']->id());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $uuid_plugin */
$uuid_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:uuid');
$uuid_plugin->setContextValue('base', $this->entities['node1']);
$relationship = $uuid_plugin->getRelationship();
$this->assertTrue($relationship instanceof ContextInterface);
$this->assertTrue($relationship->getContextDefinition()->getDataType() == 'string');
$this->assertTrue($relationship->hasContextValue());
$this->assertTrue($relationship->getContextValue() == $this->entities['node1']->uuid());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $title_plugin */
$title_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:title');
$title_plugin->setContextValue('base', $this->entities['node1']);
$relationship = $title_plugin->getRelationship();
$this->assertTrue($relationship instanceof ContextInterface);
$this->assertTrue($relationship->getContextDefinition()->getDataType() == 'string');
$this->assertTrue($relationship->hasContextValue());
$this->assertTrue($relationship->getContextValue() == $this->entities['node1']->label());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $body_plugin */
$body_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:body');
$body_plugin->setContextValue('base', $this->entities['node1']);
$relationship = $body_plugin->getRelationship();
$this->assertTrue($relationship instanceof ContextInterface);
$this->assertTrue($relationship->getContextDefinition()->getDataType() == 'string');
$this->assertTrue($relationship->hasContextValue());
$this->assertTrue($relationship->getContextValue() == $this->entities['node1']->get('body')->first()->get('value')->getValue());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $uid_plugin */
$uid_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:node:uid');
$uid_plugin->setContextValue('base', $this->entities['node3']);
$relationship = $uid_plugin->getRelationship();
$this->assertTrue($relationship instanceof ContextInterface);
$this->assertTrue($relationship->getContextDefinition()->getDataType() == 'integer');
$this->assertTrue($relationship->hasContextValue());
$this->assertTrue($relationship->getContextValue() == $this->entities['node3']->getOwnerId());
/** @var \Drupal\ctools\Plugin\RelationshipInterface $mail_plugin */
$mail_plugin = $this->relationshipManager->createInstance('typed_data_relationship:entity:user:mail');
$mail_plugin->setContextValue('base', $this->entities['user']);
$relationship = $mail_plugin->getRelationship();
$this->assertTrue($relationship instanceof ContextInterface);
$this->assertTrue($relationship->getContextDefinition()->getDataType() == 'email');
$this->assertTrue($relationship->hasContextValue());
$this->assertTrue($relationship->getContextValue() == $this->entities['user']->getEmail());
}
}

View file

@ -0,0 +1,105 @@
<?php
namespace Drupal\Tests\ctools\Kernel;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\User;
/**
* @coversDefaultClass \Drupal\ctools\TypedDataResolver
*
* @group CTools
*/
class TypedDataResolverTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['user', 'system', 'entity_test', 'ctools'];
/**
* @var \Drupal\ctools\TypedDataResolver
*/
protected $typedDataResolver;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->typedDataResolver = \Drupal::service('ctools.typed_data.resolver');
}
/**
* Tests context extraction from properties.
*/
public function testGetContextFromProperty() {
// Create a user and test entity to extract context from.
$user = User::create(['uid' => 2, 'name' => 'username', 'mail' => 'mail@example.org']);
$user->enforceIsNew(TRUE);
$user->save();
$entity_test = EntityTest::create(['user_id' => $user->id(), 'name' => 'Test name']);
// Test the language property.
$property_context = $this->assertPropertyPath($entity_test, 'langcode:language', 'language');
$this->assertEquals('en', $property_context->getContextValue()->getId());
// Test the reference to the user.
$property_context = $this->assertPropertyPath($entity_test, 'user_id:entity', 'entity:user');
$this->assertEquals($user->id(), $property_context->getContextValue()->id());
// Test the reference to the name.
$property_context = $this->assertPropertyPath($entity_test, 'name:value', 'string');
$this->assertEquals('Test name', $property_context->getContextValue());
// Test explicitly specifying the delta.
$property_context = $this->assertPropertyPath($entity_test, 'name:0:value', 'string');
$this->assertEquals('Test name', $property_context->getContextValue());
// Test following the reference.
$property_context = $this->assertPropertyPath($entity_test, 'user_id:entity:mail:value', 'email');
$this->assertEquals('mail@example.org', $property_context->getContextValue());
}
/**
* Asserts that a context for the given property path can be derived.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to test with.
* @param $property_path
* The property path to look for.
* @param $expected_data_type
* The expected data type.
*
* @return \Drupal\Core\Plugin\Context\ContextInterface
* The context with a value.
*/
protected function assertPropertyPath(ContentEntityInterface $entity, $property_path, $expected_data_type) {
$typed_data_entity = $entity->getTypedData();
$context_definition = new ContextDefinition($typed_data_entity->getDataDefinition()->getDataType());
$context_with_value = new Context($context_definition, $typed_data_entity);
$context_without_value = new Context($context_definition);
// Test the context without value.
$property_context = $this->typedDataResolver->getContextFromProperty($property_path, $context_without_value);
$this->assertEquals($expected_data_type, $property_context->getContextDefinition()->getDataType());
// Test the context with value.
$property_context = $this->typedDataResolver->getContextFromProperty($property_path, $context_with_value);
$this->assertEquals($expected_data_type, $property_context->getContextDefinition()->getDataType());
// Return the context with value so it can be asserted.
return $property_context;
}
}

View file

@ -0,0 +1,90 @@
<?php
namespace Drupal\Tests\ctools\Unit;
use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Block\BlockManager;
use Drupal\Core\Condition\ConditionManager;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Utility\Token;
use Drupal\ctools\Plugin\DisplayVariant\BlockDisplayVariant;
use Drupal\Tests\UnitTestCase;
/**
* Tests the block display variant plugin.
*
* @coversDefaultClass \Drupal\ctools\Plugin\DisplayVariant\BlockDisplayVariant
*
* @group CTools
*/
class BlockDisplayVariantTest extends UnitTestCase {
/**
* Tests the submitConfigurationForm() method.
*
* @covers ::submitConfigurationForm
*
* @dataProvider providerTestSubmitConfigurationForm
*/
public function testSubmitConfigurationForm($values) {
$account = $this->prophesize(AccountInterface::class);
$context_handler = $this->prophesize(ContextHandlerInterface::class);
$uuid_generator = $this->prophesize(UuidInterface::class);
$token = $this->prophesize(Token::class);
$block_manager = $this->prophesize(BlockManager::class);
$condition_manager = $this->prophesize(ConditionManager::class);
$display_variant = new TestBlockDisplayVariant([], '', [], $context_handler->reveal(), $account->reveal(), $uuid_generator->reveal(), $token->reveal(), $block_manager->reveal(), $condition_manager->reveal());
$form = [];
$form_state = (new FormState())->setValues($values);
$display_variant->submitConfigurationForm($form, $form_state);
$this->assertSame($values['label'], $display_variant->label());
}
/**
* Provides data for testSubmitConfigurationForm().
*/
public function providerTestSubmitConfigurationForm() {
$data = [];
$data[] = [
[
'label' => 'test_label1',
],
];
$data[] = [
[
'label' => 'test_label2',
'blocks' => ['foo1' => []],
],
];
$data[] = [
[
'label' => 'test_label3',
'blocks' => ['foo1' => [], 'foo2' => []],
],
];
return $data;
}
}
class TestBlockDisplayVariant extends BlockDisplayVariant {
/**
* {@inheritdoc}
*/
public function build() {
return [];
}
public function getRegionNames() {
return [
'top' => 'Top',
'bottom' => 'Bottom',
];
}
}

View file

@ -0,0 +1,81 @@
<?php
namespace Drupal\Tests\ctools\Unit;
use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\ctools\Plugin\BlockPluginCollection;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
/**
* Tests the block plugin collection.
*
* @coversDefaultClass \Drupal\ctools\Plugin\BlockPluginCollection
*
* @group CTools
*/
class BlockPluginCollectionTest extends UnitTestCase {
/**
* Tests the getAllByRegion() method.
*
* @covers ::getAllByRegion
*/
public function testGetAllByRegion() {
$blocks = [
'foo' => [
'id' => 'foo',
'label' => 'Foo',
'plugin' => 'system_powered_by_block',
'region' => 'bottom',
],
'bar' => [
'id' => 'bar',
'label' => 'Bar',
'plugin' => 'system_powered_by_block',
'region' => 'top',
],
'bing' => [
'id' => 'bing',
'label' => 'Bing',
'plugin' => 'system_powered_by_block',
'region' => 'bottom',
'weight' => -10,
],
'baz' => [
'id' => 'baz',
'label' => 'Baz',
'plugin' => 'system_powered_by_block',
'region' => 'bottom',
],
];
$block_manager = $this->prophesize(BlockManagerInterface::class);
$plugins = [];
foreach ($blocks as $block_id => $block) {
$plugin = $this->prophesize(BlockPluginInterface::class);
$plugin->label()->willReturn($block['label']);
$plugin->getConfiguration()->willReturn($block);
$plugins[$block_id] = $plugin->reveal();
$block_manager->createInstance($block_id, $block)
->willReturn($plugin->reveal())
->shouldBeCalled();
}
$block_plugin_collection = new BlockPluginCollection($block_manager->reveal(), $blocks);
$expected = [
'bottom' => [
'bing' => $plugins['bing'],
'baz' => $plugins['baz'],
'foo' => $plugins['foo'],
],
'top' => [
'bar' => $plugins['bar'],
],
];
$this->assertSame($expected, $block_plugin_collection->getAllByRegion());
}
}

View file

@ -0,0 +1,149 @@
<?php
namespace Drupal\Tests\ctools\Unit;
use Drupal\Component\Uuid\UuidInterface;
use Drupal\ctools\Plugin\BlockPluginCollection;
use Drupal\ctools\Plugin\BlockVariantTrait;
use Drupal\Tests\UnitTestCase;
/**
* Tests the methods of a block-based variant.
*
* @coversDefaultClass \Drupal\ctools\Plugin\BlockVariantTrait
*
* @group CTools
*/
class BlockVariantTraitTest extends UnitTestCase {
/**
* Tests the getRegionAssignments() method.
*
* @covers ::getRegionAssignments
*
* @dataProvider providerTestGetRegionAssignments
*/
public function testGetRegionAssignments($expected, $blocks = []) {
$block_collection = $this->prophesize(BlockPluginCollection::class);
$block_collection->getAllByRegion()
->willReturn($blocks)
->shouldBeCalled();
$display_variant = new TestBlockVariantTrait();
$display_variant->setBlockPluginCollection($block_collection->reveal());
$this->assertSame($expected, $display_variant->getRegionAssignments());
}
public function providerTestGetRegionAssignments() {
return [
[
[
'top' => [],
'bottom' => [],
],
],
[
[
'top' => ['foo'],
'bottom' => [],
],
[
'top' => ['foo'],
],
],
[
[
'top' => [],
'bottom' => [],
],
[
'invalid' => ['foo'],
],
],
[
[
'top' => [],
'bottom' => ['foo'],
],
[
'bottom' => ['foo'],
'invalid' => ['bar'],
],
],
];
}
}
class TestBlockVariantTrait {
use BlockVariantTrait;
/**
* @var array
*/
protected $blockConfig = [];
/**
* @var \Drupal\Component\Uuid\UuidInterface
*/
protected $uuidGenerator;
/**
* @param BlockPluginCollection $block_plugin_collection
*
* @return $this
*/
public function setBlockPluginCollection(BlockPluginCollection $block_plugin_collection) {
$this->blockPluginCollection = $block_plugin_collection;
return $this;
}
/**
* @param \Drupal\Component\Uuid\UuidInterface $uuid_generator
*
* @return $this
*/
public function setUuidGenerator(UuidInterface $uuid_generator) {
$this->uuidGenerator = $uuid_generator;
return $this;
}
/**
* {@inheritdoc}
*/
protected function uuidGenerator() {
return $this->uuidGenerator;
}
/**
* Sets the block configuration.
*
* @param array $config
* The block configuration.
*
* @return $this
*/
public function setBlockConfig(array $config) {
$this->blockConfig = $config;
return $this;
}
/**
* {@inheritdoc}
*/
protected function getBlockConfig() {
return $this->blockConfig;
}
/**
* {@inheritdoc}
*/
public function getRegionNames() {
return [
'top' => 'Top',
'bottom' => 'Bottom',
];
}
}

View file

@ -0,0 +1,104 @@
<?php
namespace Drupal\Tests\ctools\Unit;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\Plugin\DataType\IntegerData;
use Drupal\Core\TypedData\TypedDataManager;
use Drupal\ctools\Context\EntityLazyLoadContext;
use Drupal\ctools\ContextMapper;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\ctools\ContextMapper
*
* @group CTools
*/
class ContextMapperTest extends UnitTestCase {
/**
* The typed data manager.
*
* @var \Drupal\Core\TypedData\TypedDataManager|\Prophecy\Prophecy\ProphecyInterface
*/
protected $typedDataManager;
/**
* @var \Drupal\Core\Entity\EntityRepositoryInterface|\Prophecy\Prophecy\ProphecyInterface
*/
protected $entityRepository;
/**
* @var \Drupal\page_manager\ContextMapper
*/
protected $staticContext;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->typedDataManager = $this->prophesize(TypedDataManager::class);
$this->entityRepository = $this->prophesize(EntityRepositoryInterface::class);
$this->staticContext = new ContextMapper($this->entityRepository->reveal());
$container = new ContainerBuilder();
$container->set('typed_data_manager', $this->typedDataManager->reveal());
\Drupal::setContainer($container);
}
/**
* @covers ::getContextValues
*/
public function testGetContextValues() {
$input = [];
$actual = $this->staticContext->getContextValues($input);
$this->assertEquals([], $actual);
}
/**
* @covers ::getContextValues
*/
public function testGetContextValuesContext() {
$data_definition = DataDefinition::createFromDataType('integer');
$typed_data = IntegerData::createInstance($data_definition);
$this->typedDataManager->createDataDefinition('integer')->willReturn($data_definition);
$this->typedDataManager->getDefaultConstraints($data_definition)->willReturn([]);
$this->typedDataManager->create($data_definition, 5)->willReturn($typed_data);
$input = [
'foo' => [
'label' => 'Foo',
'description' => NULL,
'type' => 'integer',
'value' => 5,
],
];
$expected = new Context(new ContextDefinition('integer', 'Foo'), 5);
$actual = $this->staticContext->getContextValues($input)['foo'];
$this->assertEquals($expected, $actual);
}
/**
* @covers ::getContextValues
*/
public function testGetContextValuesEntityContext() {
$input = [
'foo' => [
'label' => 'Foo',
'description' => NULL,
'type' => 'entity:node',
'value' => 'the_node_uuid',
],
];
$expected = new EntityLazyLoadContext(new ContextDefinition('entity:node', 'Foo'), $this->entityRepository->reveal(), 'the_node_uuid');
$actual = $this->staticContext->getContextValues($input)['foo'];
$this->assertEquals($expected, $actual);
}
}

View file

@ -0,0 +1,209 @@
<?php
namespace Drupal\Tests\ctools\Unit;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Display\VariantInterface;
use Drupal\ctools\Plugin\VariantCollectionTrait;
use Drupal\ctools\Plugin\VariantPluginCollection;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
/**
* Tests the methods of a variant-aware class.
*
* @coversDefaultClass \Drupal\ctools\Plugin\VariantCollectionTrait
*
* @group Ctools
*/
class VariantCollectionTraitTest extends UnitTestCase {
/**
* @var \Drupal\Component\Plugin\PluginManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $manager;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$container = new ContainerBuilder();
$this->manager = $this->prophesize(PluginManagerInterface::class);
$container->set('plugin.manager.display_variant', $this->manager->reveal());
\Drupal::setContainer($container);
}
/**
* @covers ::getVariants
*/
public function testGetVariantsEmpty() {
$trait_object = new TestVariantCollectionTrait();
$this->manager->createInstance()->shouldNotBeCalled();
$variants = $trait_object->getVariants();
$this->assertInstanceOf(VariantPluginCollection::class, $variants);
$this->assertSame(0, count($variants));
}
/**
* @covers ::getVariants
*/
public function testGetVariants() {
$trait_object = new TestVariantCollectionTrait();
$config = [
'foo' => ['id' => 'foo_plugin'],
'bar' => ['id' => 'bar_plugin'],
];
foreach ($config as $value) {
$plugin = $this->prophesize(VariantInterface::class);
$this->manager->createInstance($value['id'], $value)->willReturn($plugin->reveal());
}
$trait_object->setVariantConfig($config);
$variants = $trait_object->getVariants();
$this->assertInstanceOf(VariantPluginCollection::class, $variants);
$this->assertSame(2, count($variants));
return $variants;
}
/**
* @covers ::getVariants
*
* @depends testGetVariants
*/
public function testGetVariantsSort(VariantPluginCollection $variants) {
$this->assertSame(['bar' => 'bar', 'foo' => 'foo'], $variants->getInstanceIds());
}
/**
* @covers ::addVariant
*/
public function testAddVariant() {
$config = ['id' => 'foo'];
$uuid = 'test-uuid';
$expected_config = $config + ['uuid' => $uuid];
$uuid_generator = $this->prophesize(UuidInterface::class);
$uuid_generator->generate()
->willReturn($uuid)
->shouldBeCalledTimes(1);
$trait_object = new TestVariantCollectionTrait();
$trait_object->setUuidGenerator($uuid_generator->reveal());
$plugin_prophecy = $this->prophesize(VariantInterface::class);
$plugin_prophecy->getConfiguration()
->willReturn($expected_config)
->shouldBeCalled();
$plugin_prophecy->setConfiguration($expected_config)
->willReturn($expected_config)
->shouldBeCalled();
$this->manager->createInstance('foo', $expected_config)
->willReturn($plugin_prophecy->reveal());
$resulting_uuid = $trait_object->addVariant($config);
$this->assertSame($uuid, $resulting_uuid);
$variants = $trait_object->getVariants();
$this->assertSame([$uuid => $uuid], $variants->getInstanceIds());
$this->assertSame([$uuid => $expected_config], $variants->getConfiguration());
$this->assertSame($plugin_prophecy->reveal(), $variants->get($uuid));
return [$trait_object, $uuid, $plugin_prophecy->reveal()];
}
/**
* @covers ::getVariant
*
* @depends testAddVariant
*/
public function testGetVariant($data) {
list($trait_object, $uuid, $plugin) = $data;
$this->manager->createInstance()->shouldNotBeCalled();
$this->assertSame($plugin, $trait_object->getVariant($uuid));
return [$trait_object, $uuid];
}
/**
* @covers ::removeVariant
*
* @depends testGetVariant
*/
public function testRemoveVariant($data) {
list($trait_object, $uuid) = $data;
$this->assertSame($trait_object, $trait_object->removeVariant($uuid));
$this->assertFalse($trait_object->getVariants()->has($uuid));
return [$trait_object, $uuid];
}
/**
* @covers ::getVariant
*
* @depends testRemoveVariant
*
* @expectedException \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @expectedExceptionMessage Plugin ID 'test-uuid' was not found.
*/
public function testGetVariantException($data) {
list($trait_object, $uuid) = $data;
// Attempt to retrieve a variant that has been removed.
$this->assertNull($trait_object->getVariant($uuid));
}
}
class TestVariantCollectionTrait {
use VariantCollectionTrait;
/**
* @var array
*/
protected $variantConfig = [];
/**
* @var \Drupal\Component\Uuid\UuidInterface
*/
protected $uuidGenerator;
/**
* @param \Drupal\Component\Uuid\UuidInterface $uuid_generator
*
* @return $this
*/
public function setUuidGenerator(UuidInterface $uuid_generator) {
$this->uuidGenerator = $uuid_generator;
return $this;
}
/**
* {@inheritdoc}
*/
protected function uuidGenerator() {
return $this->uuidGenerator;
}
/**
* Sets the variant configuration.
*
* @param array $config
* The variant configuration.
*
* @return $this
*/
public function setVariantConfig(array $config) {
$this->variantConfig = $config;
return $this;
}
/**
* {@inheritdoc}
*/
protected function getVariantConfig() {
return $this->variantConfig;
}
}