upgrades core to 8.4.2
This commit is contained in:
@@ -6,8 +6,8 @@ package: Core
|
||||
# core: 8.x
|
||||
configure: entity.action.collection
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -15,6 +15,6 @@ function action_views_form_substitutions() {
|
||||
'#attributes' => ['class' => ['action-table-select-all']],
|
||||
];
|
||||
return [
|
||||
'<!--action-bulk-form-select-all-->' => drupal_render($select_all),
|
||||
'<!--action-bulk-form-select-all-->' => \Drupal::service('renderer')->render($select_all),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ source:
|
||||
plugin: variable
|
||||
variables:
|
||||
- actions_max_stack
|
||||
source_module: action
|
||||
process:
|
||||
recursion_limit: actions_max_stack
|
||||
destination:
|
||||
|
||||
@@ -92,7 +92,7 @@ class GotoAction extends ConfigurableActionBase implements ContainerFactoryPlugi
|
||||
$url = $this->unroutedUrlAssembler->assemble($uri, $options);
|
||||
}
|
||||
$response = new RedirectResponse($url);
|
||||
$listener = function($event) use ($response) {
|
||||
$listener = function ($event) use ($response) {
|
||||
$event->setResponse($response);
|
||||
};
|
||||
// Add the listener to the event dispatcher.
|
||||
|
||||
@@ -10,7 +10,7 @@ use Drupal\migrate\Row;
|
||||
*
|
||||
* @MigrateSource(
|
||||
* id = "action",
|
||||
* source_provider = "system"
|
||||
* source_module = "system"
|
||||
* )
|
||||
*/
|
||||
class Action extends DrupalSqlBase {
|
||||
|
||||
@@ -9,8 +9,8 @@ dependencies:
|
||||
- views
|
||||
- node
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -27,7 +27,7 @@ class ActionUninstallTest extends BrowserTestBase {
|
||||
|
||||
$storage = $this->container->get('entity_type.manager')->getStorage('action');
|
||||
$storage->resetCache(['user_block_user_action']);
|
||||
$this->assertTrue($storage->load('user_block_user_action'), 'Configuration entity \'user_block_user_action\' still exists after uninstalling action module.' );
|
||||
$this->assertTrue($storage->load('user_block_user_action'), 'Configuration entity \'user_block_user_action\' still exists after uninstalling action module.');
|
||||
|
||||
$admin_user = $this->drupalCreateUser(['administer users']);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
@@ -9,8 +9,8 @@ dependencies:
|
||||
- file
|
||||
- options
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -13,6 +13,8 @@ use Drupal\Core\Routing\RouteMatchInterface;
|
||||
*
|
||||
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
|
||||
* Use \Drupal\aggregator\FeedStorageInterface::CLEAR_NEVER instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2831620
|
||||
*/
|
||||
const AGGREGATOR_CLEAR_NEVER = 0;
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ source:
|
||||
- aggregator_teaser_length
|
||||
- aggregator_clear
|
||||
- aggregator_summary_items
|
||||
source_module: aggregator
|
||||
process:
|
||||
fetcher: aggregator_fetcher
|
||||
parser: aggregator_parser
|
||||
|
||||
@@ -12,6 +12,7 @@ source:
|
||||
- aggregator_teaser_length
|
||||
- aggregator_clear
|
||||
- aggregator_summary_items
|
||||
source_module: aggregator
|
||||
process:
|
||||
fetcher: aggregator_fetcher
|
||||
parser: aggregator_parser
|
||||
|
||||
@@ -25,7 +25,7 @@ class AggregatorController extends ControllerBase {
|
||||
* Constructs a \Drupal\aggregator\Controller\AggregatorController object.
|
||||
*
|
||||
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
|
||||
* The date formatter service.
|
||||
* The date formatter service.
|
||||
*/
|
||||
public function __construct(DateFormatterInterface $date_formatter) {
|
||||
$this->dateFormatter = $date_formatter;
|
||||
|
||||
@@ -84,11 +84,13 @@ class DefaultFetcher implements FetcherInterface, ContainerFactoryPluginInterfac
|
||||
|
||||
/** @var \Psr\Http\Message\UriInterface $actual_uri */
|
||||
$actual_uri = NULL;
|
||||
$response = $this->httpClientFactory->fromOptions(['allow_redirects' => [
|
||||
'on_redirect' => function(RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
|
||||
$actual_uri = (string) $uri;
|
||||
}
|
||||
]])->send($request);
|
||||
$response = $this->httpClientFactory->fromOptions([
|
||||
'allow_redirects' => [
|
||||
'on_redirect' => function (RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
|
||||
$actual_uri = (string) $uri;
|
||||
}
|
||||
],
|
||||
])->send($request);
|
||||
|
||||
// In case of a 304 Not Modified, there is no new content, so return
|
||||
// FALSE.
|
||||
|
||||
@@ -141,7 +141,7 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
|
||||
];
|
||||
|
||||
$lengths = [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000];
|
||||
$options = array_map(function($length) {
|
||||
$options = array_map(function ($length) {
|
||||
return ($length == 0) ? t('Unlimited') : $this->formatPlural($length, '1 character', '@count characters');
|
||||
}, array_combine($lengths, $lengths));
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
|
||||
*
|
||||
* @MigrateSource(
|
||||
* id = "aggregator_feed",
|
||||
* source_provider = "aggregator"
|
||||
* source_module = "aggregator"
|
||||
* )
|
||||
*/
|
||||
class AggregatorFeed extends DrupalSqlBase {
|
||||
|
||||
@@ -9,7 +9,7 @@ use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
|
||||
*
|
||||
* @MigrateSource(
|
||||
* id = "aggregator_item",
|
||||
* source_provider = "aggregator"
|
||||
* source_module = "aggregator"
|
||||
* )
|
||||
*/
|
||||
class AggregatorItem extends DrupalSqlBase {
|
||||
|
||||
@@ -5,8 +5,8 @@ package: Testing
|
||||
# version: VERSION
|
||||
# core: 8.x
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
+3
-3
@@ -8,8 +8,8 @@ dependencies:
|
||||
- aggregator
|
||||
- views
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\aggregator\Functional\Update;
|
||||
|
||||
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
|
||||
|
||||
/**
|
||||
* Tests that node settings are properly updated during database updates.
|
||||
*
|
||||
* @group aggregator
|
||||
*/
|
||||
class AggregatorUpdateTest extends UpdatePathTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setDatabaseDumpFiles() {
|
||||
$this->databaseDumpFiles = [
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.filled.standard.php.gz',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the 'Source feed' field is required.
|
||||
*
|
||||
* @see aggregator_update_8200()
|
||||
*/
|
||||
public function testSourceFeedRequired() {
|
||||
// Check that the 'fid' field is not required prior to the update.
|
||||
$field_definition = \Drupal::entityDefinitionUpdateManager()->getFieldStorageDefinition('fid', 'aggregator_item');
|
||||
$this->assertFalse($field_definition->isRequired());
|
||||
|
||||
// Run updates.
|
||||
$this->runUpdates();
|
||||
|
||||
// Check that the 'fid' field is now required.
|
||||
$field_definition = \Drupal::entityDefinitionUpdateManager()->getFieldStorageDefinition('fid', 'aggregator_item');
|
||||
$this->assertTrue($field_definition->isRequired());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\aggregator\Functional;
|
||||
|
||||
use Drupal\aggregator\Entity\Feed;
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,6 @@ use Drupal\aggregator\Entity\Feed;
|
||||
use Drupal\aggregator\Entity\Item;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
||||
|
||||
/**
|
||||
* Tests the aggregator_title formatter.
|
||||
*
|
||||
|
||||
@@ -6,8 +6,8 @@ package: Core
|
||||
# core: 8.x
|
||||
configure: system.cron_settings
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -6,8 +6,8 @@ package: Core
|
||||
# core: 8.x
|
||||
configure: ban.admin_page
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -9,7 +9,7 @@ use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
|
||||
*
|
||||
* @MigrateSource(
|
||||
* id = "d7_blocked_ips",
|
||||
* source_provider = "system"
|
||||
* source_module = "system"
|
||||
* )
|
||||
*/
|
||||
class BlockedIps extends DrupalSqlBase {
|
||||
|
||||
@@ -7,8 +7,8 @@ package: Web services
|
||||
dependencies:
|
||||
- user
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -5,8 +5,8 @@ package: Testing
|
||||
# version: VERSION
|
||||
# core: 8.x
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -5,8 +5,8 @@ package: Core
|
||||
# version: VERSION
|
||||
# core: 8.x
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* @file
|
||||
* Renders BigPipe placeholders using Drupal's Ajax system.
|
||||
*/
|
||||
|
||||
(function ($, Drupal, drupalSettings) {
|
||||
/**
|
||||
* Executes Ajax commands in <script type="application/vnd.drupal-ajax"> tag.
|
||||
*
|
||||
* These Ajax commands replace placeholders with HTML and load missing CSS/JS.
|
||||
*
|
||||
* @param {number} index
|
||||
* Current index.
|
||||
* @param {HTMLScriptElement} placeholderReplacement
|
||||
* Script tag created by BigPipe.
|
||||
*/
|
||||
function bigPipeProcessPlaceholderReplacement(index, placeholderReplacement) {
|
||||
const placeholderId = placeholderReplacement.getAttribute('data-big-pipe-replacement-for-placeholder-with-id');
|
||||
const content = this.textContent.trim();
|
||||
// Ignore any placeholders that are not in the known placeholder list. Used
|
||||
// to avoid someone trying to XSS the site via the placeholdering mechanism.
|
||||
if (typeof drupalSettings.bigPipePlaceholderIds[placeholderId] !== 'undefined') {
|
||||
// If we try to parse the content too early (when the JSON containing Ajax
|
||||
// commands is still arriving), textContent will be empty which will cause
|
||||
// JSON.parse() to fail. Remove once so that it can be processed again
|
||||
// later.
|
||||
// @see bigPipeProcessDocument()
|
||||
if (content === '') {
|
||||
$(this).removeOnce('big-pipe');
|
||||
}
|
||||
else {
|
||||
const response = JSON.parse(content);
|
||||
// Create a Drupal.Ajax object without associating an element, a
|
||||
// progress indicator or a URL.
|
||||
const ajaxObject = Drupal.ajax({
|
||||
url: '',
|
||||
base: false,
|
||||
element: false,
|
||||
progress: false,
|
||||
});
|
||||
// Then, simulate an AJAX response having arrived, and let the Ajax
|
||||
// system handle it.
|
||||
ajaxObject.success(response, 'success');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a streamed HTML document receiving placeholder replacements.
|
||||
*
|
||||
* @param {HTMLDocument} context
|
||||
* The HTML document containing <script type="application/vnd.drupal-ajax">
|
||||
* tags generated by BigPipe.
|
||||
*
|
||||
* @return {bool}
|
||||
* Returns true when processing has been finished and a stop signal has been
|
||||
* found.
|
||||
*/
|
||||
function bigPipeProcessDocument(context) {
|
||||
// Make sure we have BigPipe-related scripts before processing further.
|
||||
if (!context.querySelector('script[data-big-pipe-event="start"]')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$(context).find('script[data-big-pipe-replacement-for-placeholder-with-id]')
|
||||
.once('big-pipe')
|
||||
.each(bigPipeProcessPlaceholderReplacement);
|
||||
|
||||
// If we see the stop signal, clear the timeout: all placeholder
|
||||
// replacements are guaranteed to be received and processed.
|
||||
if (context.querySelector('script[data-big-pipe-event="stop"]')) {
|
||||
if (timeoutID) {
|
||||
clearTimeout(timeoutID);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function bigPipeProcess() {
|
||||
timeoutID = setTimeout(() => {
|
||||
if (!bigPipeProcessDocument(document)) {
|
||||
bigPipeProcess();
|
||||
}
|
||||
}, interval);
|
||||
}
|
||||
|
||||
// The frequency with which to check for newly arrived BigPipe placeholders.
|
||||
// Hence 50 ms means we check 20 times per second. Setting this to 100 ms or
|
||||
// more would cause the user to see content appear noticeably slower.
|
||||
var interval = drupalSettings.bigPipeInterval || 50;
|
||||
// The internal ID to contain the watcher service.
|
||||
let timeoutID;
|
||||
|
||||
bigPipeProcess();
|
||||
|
||||
// If something goes wrong, make sure everything is cleaned up and has had a
|
||||
// chance to be processed with everything loaded.
|
||||
$(window).on('load', () => {
|
||||
if (timeoutID) {
|
||||
clearTimeout(timeoutID);
|
||||
}
|
||||
bigPipeProcessDocument(document);
|
||||
});
|
||||
}(jQuery, Drupal, drupalSettings));
|
||||
@@ -1,76 +1,40 @@
|
||||
/**
|
||||
* @file
|
||||
* Renders BigPipe placeholders using Drupal's Ajax system.
|
||||
*/
|
||||
* DO NOT EDIT THIS FILE.
|
||||
* See the following change record for more information,
|
||||
* https://www.drupal.org/node/2815083
|
||||
* @preserve
|
||||
**/
|
||||
|
||||
(function ($, Drupal, drupalSettings) {
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Executes Ajax commands in <script type="application/vnd.drupal-ajax"> tag.
|
||||
*
|
||||
* These Ajax commands replace placeholders with HTML and load missing CSS/JS.
|
||||
*
|
||||
* @param {number} index
|
||||
* Current index.
|
||||
* @param {HTMLScriptElement} placeholderReplacement
|
||||
* Script tag created by BigPipe.
|
||||
*/
|
||||
function bigPipeProcessPlaceholderReplacement(index, placeholderReplacement) {
|
||||
var placeholderId = placeholderReplacement.getAttribute('data-big-pipe-replacement-for-placeholder-with-id');
|
||||
var content = this.textContent.trim();
|
||||
// Ignore any placeholders that are not in the known placeholder list. Used
|
||||
// to avoid someone trying to XSS the site via the placeholdering mechanism.
|
||||
|
||||
if (typeof drupalSettings.bigPipePlaceholderIds[placeholderId] !== 'undefined') {
|
||||
// If we try to parse the content too early (when the JSON containing Ajax
|
||||
// commands is still arriving), textContent will be empty which will cause
|
||||
// JSON.parse() to fail. Remove once so that it can be processed again
|
||||
// later.
|
||||
// @see bigPipeProcessDocument()
|
||||
if (content === '') {
|
||||
$(this).removeOnce('big-pipe');
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
var response = JSON.parse(content);
|
||||
// Create a Drupal.Ajax object without associating an element, a
|
||||
// progress indicator or a URL.
|
||||
|
||||
var ajaxObject = Drupal.ajax({
|
||||
url: '',
|
||||
base: false,
|
||||
element: false,
|
||||
progress: false
|
||||
});
|
||||
// Then, simulate an AJAX response having arrived, and let the Ajax
|
||||
// system handle it.
|
||||
|
||||
ajaxObject.success(response, 'success');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes a streamed HTML document receiving placeholder replacements.
|
||||
*
|
||||
* @param {HTMLDocument} context
|
||||
* The HTML document containing <script type="application/vnd.drupal-ajax">
|
||||
* tags generated by BigPipe.
|
||||
*
|
||||
* @return {bool}
|
||||
* Returns true when processing has been finished and a stop signal has been
|
||||
* found.
|
||||
*/
|
||||
function bigPipeProcessDocument(context) {
|
||||
// Make sure we have BigPipe-related scripts before processing further.
|
||||
if (!context.querySelector('script[data-big-pipe-event="start"]')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$(context).find('script[data-big-pipe-replacement-for-placeholder-with-id]')
|
||||
.once('big-pipe')
|
||||
.each(bigPipeProcessPlaceholderReplacement);
|
||||
$(context).find('script[data-big-pipe-replacement-for-placeholder-with-id]').once('big-pipe').each(bigPipeProcessPlaceholderReplacement);
|
||||
|
||||
// If we see the stop signal, clear the timeout: all placeholder
|
||||
// replacements are guaranteed to be received and processed.
|
||||
if (context.querySelector('script[data-big-pipe-event="stop"]')) {
|
||||
if (timeoutID) {
|
||||
clearTimeout(timeoutID);
|
||||
@@ -89,22 +53,16 @@
|
||||
}, interval);
|
||||
}
|
||||
|
||||
// The frequency with which to check for newly arrived BigPipe placeholders.
|
||||
// Hence 50 ms means we check 20 times per second. Setting this to 100 ms or
|
||||
// more would cause the user to see content appear noticeably slower.
|
||||
var interval = drupalSettings.bigPipeInterval || 50;
|
||||
// The internal ID to contain the watcher service.
|
||||
var timeoutID;
|
||||
|
||||
var timeoutID = void 0;
|
||||
|
||||
bigPipeProcess();
|
||||
|
||||
// If something goes wrong, make sure everything is cleaned up and has had a
|
||||
// chance to be processed with everything loaded.
|
||||
$(window).on('load', function () {
|
||||
if (timeoutID) {
|
||||
clearTimeout(timeoutID);
|
||||
}
|
||||
bigPipeProcessDocument(document);
|
||||
});
|
||||
|
||||
})(jQuery, Drupal, drupalSettings);
|
||||
})(jQuery, Drupal, drupalSettings);
|
||||
@@ -109,7 +109,7 @@ class BigPipeStrategy implements PlaceholderStrategyInterface {
|
||||
$request = $this->requestStack->getCurrentRequest();
|
||||
|
||||
// @todo remove this check when https://www.drupal.org/node/2367555 lands.
|
||||
if (!$request->isMethodSafe()) {
|
||||
if (!$request->isMethodCacheable()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -5,8 +5,8 @@ package: Testing
|
||||
# version: VERSION
|
||||
# core: 8.x
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -5,8 +5,8 @@ package: Testing
|
||||
# version: VERSION
|
||||
# core: 8.x
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
*/
|
||||
|
||||
namespace Drupal\big_pipe_test;
|
||||
|
||||
use Drupal\big_pipe\Render\BigPipeMarkup;
|
||||
use Drupal\Core\Session\AccountInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* BigPipe placeholder test cases for use in both unit and integration tests.
|
||||
*
|
||||
* - Unit test:
|
||||
* \Drupal\Tests\big_pipe\Unit\Render\Placeholder\BigPipeStrategyTest
|
||||
* - Integration test for BigPipe with JS on:
|
||||
* \Drupal\Tests\big_pipe\Functional\BigPipeTest::testBigPipe()
|
||||
* - Integration test for BigPipe with JS off:
|
||||
* \Drupal\Tests\big_pipe\Functional\BigPipeTest::testBigPipeNoJs()
|
||||
*/
|
||||
class BigPipePlaceholderTestCases {
|
||||
|
||||
/**
|
||||
* Gets all BigPipe placeholder test cases.
|
||||
*
|
||||
* @param \Symfony\Component\DependencyInjection\ContainerInterface|null $container
|
||||
* Optional. Necessary to get the embedded AJAX/HTML responses.
|
||||
* @param \Drupal\Core\Session\AccountInterface|null $user
|
||||
* Optional. Necessary to get the embedded AJAX/HTML responses.
|
||||
*
|
||||
* @return \Drupal\big_pipe_test\BigPipePlaceholderTestCase[]
|
||||
*/
|
||||
public static function cases(ContainerInterface $container = NULL, AccountInterface $user = NULL) {
|
||||
// Define the two types of cacheability that we expect to see. These will be
|
||||
// used in the expectations.
|
||||
$cacheability_depends_on_session_only = [
|
||||
'max-age' => 0,
|
||||
'contexts' => ['session.exists'],
|
||||
];
|
||||
$cacheability_depends_on_session_and_nojs_cookie = [
|
||||
'max-age' => 0,
|
||||
'contexts' => ['session.exists', 'cookies:big_pipe_nojs'],
|
||||
];
|
||||
|
||||
|
||||
// 1. Real-world example of HTML placeholder.
|
||||
$status_messages = new BigPipePlaceholderTestCase(
|
||||
['#type' => 'status_messages'],
|
||||
'<drupal-render-placeholder callback="Drupal\Core\Render\Element\StatusMessages::renderMessages" arguments="0" token="_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA"></drupal-render-placeholder>',
|
||||
[
|
||||
'#lazy_builder' => [
|
||||
'Drupal\Core\Render\Element\StatusMessages::renderMessages',
|
||||
[NULL]
|
||||
],
|
||||
]
|
||||
);
|
||||
$status_messages->bigPipePlaceholderId = 'callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA';
|
||||
$status_messages->bigPipePlaceholderRenderArray = [
|
||||
'#markup' => '<span data-big-pipe-placeholder-id="callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA"></span>',
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'library' => ['big_pipe/big_pipe'],
|
||||
'drupalSettings' => [
|
||||
'bigPipePlaceholderIds' => [
|
||||
'callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA' => TRUE,
|
||||
],
|
||||
],
|
||||
'big_pipe_placeholders' => [
|
||||
'callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA' => $status_messages->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$status_messages->bigPipeNoJsPlaceholder = '<span data-big-pipe-nojs-placeholder-id="callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA"></span>';
|
||||
$status_messages->bigPipeNoJsPlaceholderRenderArray = [
|
||||
'#markup' => '<span data-big-pipe-nojs-placeholder-id="callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA"></span>',
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'big_pipe_nojs_placeholders' => [
|
||||
'<span data-big-pipe-nojs-placeholder-id="callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA"></span>' => $status_messages->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
if ($container && $user) {
|
||||
$status_messages->embeddedAjaxResponseCommands = [
|
||||
[
|
||||
'command' => 'insert',
|
||||
'method' => 'replaceWith',
|
||||
'selector' => '[data-big-pipe-placeholder-id="callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA"]',
|
||||
'data' => ' <div role="contentinfo" aria-label="Status message" class="messages messages--status">' . "\n" . ' <h2 class="visually-hidden">Status message</h2>' . "\n" . ' Hello from BigPipe!' . "\n" . ' </div>' . "\n ",
|
||||
'settings' => NULL,
|
||||
],
|
||||
];
|
||||
$status_messages->embeddedHtmlResponse = '<div role="contentinfo" aria-label="Status message" class="messages messages--status">' . "\n" . ' <h2 class="visually-hidden">Status message</h2>' . "\n" . ' Hello from BigPipe!' . "\n" . ' </div>' . "\n \n";
|
||||
}
|
||||
|
||||
|
||||
// 2. Real-world example of HTML attribute value placeholder: form action.
|
||||
$form_action = new BigPipePlaceholderTestCase(
|
||||
$container ? $container->get('form_builder')->getForm('Drupal\big_pipe_test\Form\BigPipeTestForm') : [],
|
||||
'form_action_cc611e1d',
|
||||
[
|
||||
'#lazy_builder' => ['form_builder:renderPlaceholderFormAction', []],
|
||||
]
|
||||
);
|
||||
$form_action->bigPipeNoJsPlaceholder = 'big_pipe_nojs_placeholder_attribute_safe:form_action_cc611e1d';
|
||||
$form_action->bigPipeNoJsPlaceholderRenderArray = [
|
||||
'#markup' => 'big_pipe_nojs_placeholder_attribute_safe:form_action_cc611e1d',
|
||||
'#cache' => $cacheability_depends_on_session_only,
|
||||
'#attached' => [
|
||||
'big_pipe_nojs_placeholders' => [
|
||||
'big_pipe_nojs_placeholder_attribute_safe:form_action_cc611e1d' => $form_action->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
if ($container) {
|
||||
$form_action->embeddedHtmlResponse = '<form class="big-pipe-test-form" data-drupal-selector="big-pipe-test-form" action="' . base_path() . 'big_pipe_test"';
|
||||
}
|
||||
|
||||
|
||||
// 3. Real-world example of HTML attribute value subset placeholder: CSRF
|
||||
// token in link.
|
||||
$csrf_token = new BigPipePlaceholderTestCase(
|
||||
[
|
||||
'#title' => 'Link with CSRF token',
|
||||
'#type' => 'link',
|
||||
'#url' => Url::fromRoute('system.theme_set_default'),
|
||||
],
|
||||
'e88b559cce72c80b687d56b0e2a3a5ae4b66bc0e',
|
||||
[
|
||||
'#lazy_builder' => [
|
||||
'route_processor_csrf:renderPlaceholderCsrfToken',
|
||||
['admin/config/user-interface/shortcut/manage/default/add-link-inline']
|
||||
],
|
||||
]
|
||||
);
|
||||
$csrf_token->bigPipeNoJsPlaceholder = 'big_pipe_nojs_placeholder_attribute_safe:e88b559cce72c80b687d56b0e2a3a5ae4b66bc0e';
|
||||
$csrf_token->bigPipeNoJsPlaceholderRenderArray = [
|
||||
'#markup' => 'big_pipe_nojs_placeholder_attribute_safe:e88b559cce72c80b687d56b0e2a3a5ae4b66bc0e',
|
||||
'#cache' => $cacheability_depends_on_session_only,
|
||||
'#attached' => [
|
||||
'big_pipe_nojs_placeholders' => [
|
||||
'big_pipe_nojs_placeholder_attribute_safe:e88b559cce72c80b687d56b0e2a3a5ae4b66bc0e' => $csrf_token->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
if ($container) {
|
||||
$csrf_token->embeddedHtmlResponse = $container->get('csrf_token')->get('admin/appearance/default');
|
||||
}
|
||||
|
||||
|
||||
// 4. Edge case: custom string to be considered as a placeholder that
|
||||
// happens to not be valid HTML.
|
||||
$hello = new BigPipePlaceholderTestCase(
|
||||
[
|
||||
'#markup' => BigPipeMarkup::create('<hello'),
|
||||
'#attached' => [
|
||||
'placeholders' => [
|
||||
'<hello' => ['#lazy_builder' => ['\Drupal\big_pipe_test\BigPipeTestController::helloOrYarhar', []]],
|
||||
]
|
||||
],
|
||||
],
|
||||
'<hello',
|
||||
[
|
||||
'#lazy_builder' => [
|
||||
'hello_or_yarhar',
|
||||
[]
|
||||
],
|
||||
]
|
||||
);
|
||||
$hello->bigPipeNoJsPlaceholder = 'big_pipe_nojs_placeholder_attribute_safe:<hello';
|
||||
$hello->bigPipeNoJsPlaceholderRenderArray = [
|
||||
'#markup' => 'big_pipe_nojs_placeholder_attribute_safe:<hello',
|
||||
'#cache' => $cacheability_depends_on_session_only,
|
||||
'#attached' => [
|
||||
'big_pipe_nojs_placeholders' => [
|
||||
'big_pipe_nojs_placeholder_attribute_safe:<hello' => $hello->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$hello->embeddedHtmlResponse = '<marquee>Yarhar llamas forever!</marquee>';
|
||||
|
||||
|
||||
// 5. Edge case: non-#lazy_builder placeholder.
|
||||
$current_time = new BigPipePlaceholderTestCase(
|
||||
[
|
||||
'#markup' => BigPipeMarkup::create('<time>CURRENT TIME</time>'),
|
||||
'#attached' => [
|
||||
'placeholders' => [
|
||||
'<time>CURRENT TIME</time>' => [
|
||||
'#pre_render' => [
|
||||
'\Drupal\big_pipe_test\BigPipeTestController::currentTime',
|
||||
],
|
||||
]
|
||||
]
|
||||
]
|
||||
],
|
||||
'<time>CURRENT TIME</time>',
|
||||
[
|
||||
'#pre_render' => ['current_time'],
|
||||
]
|
||||
);
|
||||
$current_time->bigPipePlaceholderId = 'timecurrent-timetime';
|
||||
$current_time->bigPipePlaceholderRenderArray = [
|
||||
'#markup' => '<span data-big-pipe-placeholder-id="timecurrent-timetime"></span>',
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'library' => ['big_pipe/big_pipe'],
|
||||
'drupalSettings' => [
|
||||
'bigPipePlaceholderIds' => [
|
||||
'timecurrent-timetime' => TRUE,
|
||||
],
|
||||
],
|
||||
'big_pipe_placeholders' => [
|
||||
'timecurrent-timetime' => $current_time->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$current_time->embeddedAjaxResponseCommands = [
|
||||
[
|
||||
'command' => 'insert',
|
||||
'method' => 'replaceWith',
|
||||
'selector' => '[data-big-pipe-placeholder-id="timecurrent-timetime"]',
|
||||
'data' => '<time datetime="1991-03-14"></time>',
|
||||
'settings' => NULL,
|
||||
],
|
||||
];
|
||||
$current_time->bigPipeNoJsPlaceholder = '<span data-big-pipe-nojs-placeholder-id="timecurrent-timetime"></span>';
|
||||
$current_time->bigPipeNoJsPlaceholderRenderArray = [
|
||||
'#markup' => '<span data-big-pipe-nojs-placeholder-id="timecurrent-timetime"></span>',
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'big_pipe_nojs_placeholders' => [
|
||||
'<span data-big-pipe-nojs-placeholder-id="timecurrent-timetime"></span>' => $current_time->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$current_time->embeddedHtmlResponse = '<time datetime="1991-03-14"></time>';
|
||||
|
||||
|
||||
// 6. Edge case: #lazy_builder that throws an exception.
|
||||
$exception = new BigPipePlaceholderTestCase(
|
||||
[
|
||||
'#lazy_builder' => ['\Drupal\big_pipe_test\BigPipeTestController::exception', ['llamas', 'suck']],
|
||||
'#create_placeholder' => TRUE,
|
||||
],
|
||||
'<drupal-render-placeholder callback="\Drupal\big_pipe_test\BigPipeTestController::exception" arguments="0=llamas&1=suck" token="uhKFNfT4eF449_W-kDQX8E5z4yHyt0-nSHUlwaGAQeU"></drupal-render-placeholder>',
|
||||
[
|
||||
'#lazy_builder' => ['\Drupal\big_pipe_test\BigPipeTestController::exception', ['llamas', 'suck']],
|
||||
]
|
||||
);
|
||||
$exception->bigPipePlaceholderId = 'callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3Aexception&args%5B0%5D=llamas&args%5B1%5D=suck&token=uhKFNfT4eF449_W-kDQX8E5z4yHyt0-nSHUlwaGAQeU';
|
||||
$exception->bigPipePlaceholderRenderArray = [
|
||||
'#markup' => '<span data-big-pipe-placeholder-id="callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3Aexception&args%5B0%5D=llamas&args%5B1%5D=suck&token=uhKFNfT4eF449_W-kDQX8E5z4yHyt0-nSHUlwaGAQeU"></span>',
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'library' => ['big_pipe/big_pipe'],
|
||||
'drupalSettings' => [
|
||||
'bigPipePlaceholderIds' => [
|
||||
'callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3Aexception&args%5B0%5D=llamas&args%5B1%5D=suck&token=uhKFNfT4eF449_W-kDQX8E5z4yHyt0-nSHUlwaGAQeU' => TRUE,
|
||||
],
|
||||
],
|
||||
'big_pipe_placeholders' => [
|
||||
'callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3Aexception&args%5B0%5D=llamas&args%5B1%5D=suck&token=uhKFNfT4eF449_W-kDQX8E5z4yHyt0-nSHUlwaGAQeU' => $exception->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$exception->embeddedAjaxResponseCommands = NULL;
|
||||
$exception->bigPipeNoJsPlaceholder = '<span data-big-pipe-nojs-placeholder-id="callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3Aexception&args%5B0%5D=llamas&args%5B1%5D=suck&token=uhKFNfT4eF449_W-kDQX8E5z4yHyt0-nSHUlwaGAQeU"></span>';
|
||||
$exception->bigPipeNoJsPlaceholderRenderArray = [
|
||||
'#markup' => $exception->bigPipeNoJsPlaceholder,
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'big_pipe_nojs_placeholders' => [
|
||||
$exception->bigPipeNoJsPlaceholder => $exception->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$exception->embeddedHtmlResponse = NULL;
|
||||
|
||||
// 7. Edge case: response filter throwing an exception for this placeholder.
|
||||
$embedded_response_exception = new BigPipePlaceholderTestCase(
|
||||
[
|
||||
'#lazy_builder' => ['\Drupal\big_pipe_test\BigPipeTestController::responseException', []],
|
||||
'#create_placeholder' => TRUE,
|
||||
],
|
||||
'<drupal-render-placeholder callback="\Drupal\big_pipe_test\BigPipeTestController::responseException" arguments="" token="PxOHfS_QL-T01NjBgu7Z7I04tIwMp6La5vM-mVxezbU"></drupal-render-placeholder>',
|
||||
[
|
||||
'#lazy_builder' => ['\Drupal\big_pipe_test\BigPipeTestController::responseException', []],
|
||||
]
|
||||
);
|
||||
$embedded_response_exception->bigPipePlaceholderId = 'callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3AresponseException&&token=PxOHfS_QL-T01NjBgu7Z7I04tIwMp6La5vM-mVxezbU';
|
||||
$embedded_response_exception->bigPipePlaceholderRenderArray = [
|
||||
'#markup' => '<span data-big-pipe-placeholder-id="callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3AresponseException&&token=PxOHfS_QL-T01NjBgu7Z7I04tIwMp6La5vM-mVxezbU"></span>',
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'library' => ['big_pipe/big_pipe'],
|
||||
'drupalSettings' => [
|
||||
'bigPipePlaceholderIds' => [
|
||||
'callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3AresponseException&&token=PxOHfS_QL-T01NjBgu7Z7I04tIwMp6La5vM-mVxezbU' => TRUE,
|
||||
],
|
||||
],
|
||||
'big_pipe_placeholders' => [
|
||||
'callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3AresponseException&&token=PxOHfS_QL-T01NjBgu7Z7I04tIwMp6La5vM-mVxezbU' => $embedded_response_exception->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$embedded_response_exception->embeddedAjaxResponseCommands = NULL;
|
||||
$embedded_response_exception->bigPipeNoJsPlaceholder = '<span data-big-pipe-nojs-placeholder-id="callback=%5CDrupal%5Cbig_pipe_test%5CBigPipeTestController%3A%3AresponseException&&token=PxOHfS_QL-T01NjBgu7Z7I04tIwMp6La5vM-mVxezbU"></span>';
|
||||
$embedded_response_exception->bigPipeNoJsPlaceholderRenderArray = [
|
||||
'#markup' => $embedded_response_exception->bigPipeNoJsPlaceholder,
|
||||
'#cache' => $cacheability_depends_on_session_and_nojs_cookie,
|
||||
'#attached' => [
|
||||
'big_pipe_nojs_placeholders' => [
|
||||
$embedded_response_exception->bigPipeNoJsPlaceholder => $embedded_response_exception->placeholderRenderArray,
|
||||
],
|
||||
],
|
||||
];
|
||||
$exception->embeddedHtmlResponse = NULL;
|
||||
|
||||
return [
|
||||
'html' => $status_messages,
|
||||
'html_attribute_value' => $form_action,
|
||||
'html_attribute_value_subset' => $csrf_token,
|
||||
'edge_case__invalid_html' => $hello,
|
||||
'edge_case__html_non_lazy_builder' => $current_time,
|
||||
'exception__lazy_builder' => $exception,
|
||||
'exception__embedded_response' => $embedded_response_exception,
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class BigPipePlaceholderTestCase {
|
||||
|
||||
/**
|
||||
* The original render array.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $renderArray;
|
||||
|
||||
/**
|
||||
* The expected corresponding placeholder string.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $placeholder;
|
||||
|
||||
/**
|
||||
* The expected corresponding placeholder render array.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $placeholderRenderArray;
|
||||
|
||||
/**
|
||||
* The expected BigPipe placeholder ID.
|
||||
*
|
||||
* (Only possible for HTML placeholders.)
|
||||
*
|
||||
* @var null|string
|
||||
*/
|
||||
public $bigPipePlaceholderId = NULL;
|
||||
|
||||
/**
|
||||
* The corresponding expected BigPipe placeholder render array.
|
||||
*
|
||||
* @var null|array
|
||||
*/
|
||||
public $bigPipePlaceholderRenderArray = NULL;
|
||||
|
||||
/**
|
||||
* The corresponding expected embedded AJAX response.
|
||||
*
|
||||
* @var null|array
|
||||
*/
|
||||
public $embeddedAjaxResponseCommands = NULL;
|
||||
|
||||
|
||||
/**
|
||||
* The expected BigPipe no-JS placeholder.
|
||||
*
|
||||
* (Possible for all placeholders, HTML or non-HTML.)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $bigPipeNoJsPlaceholder;
|
||||
|
||||
/**
|
||||
* The corresponding expected BigPipe no-JS placeholder render array.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $bigPipeNoJsPlaceholderRenderArray;
|
||||
|
||||
/**
|
||||
* The corresponding expected embedded HTML response.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $embeddedHtmlResponse;
|
||||
|
||||
public function __construct(array $render_array, $placeholder, array $placeholder_render_array) {
|
||||
$this->renderArray = $render_array;
|
||||
$this->placeholder = $placeholder;
|
||||
$this->placeholderRenderArray = $placeholder_render_array;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace Drupal\big_pipe_test;
|
||||
|
||||
use Drupal\big_pipe\Render\BigPipeMarkup;
|
||||
use Drupal\big_pipe\Tests\BigPipePlaceholderTestCases;
|
||||
use Drupal\big_pipe_test\EventSubscriber\BigPipeTestSubscriber;
|
||||
|
||||
class BigPipeTestController {
|
||||
@@ -61,7 +60,7 @@ class BigPipeTestController {
|
||||
/**
|
||||
* A page with multiple occurrences of the same placeholder.
|
||||
*
|
||||
* @see \Drupal\big_pipe\Tests\BigPipeTest::testBigPipeMultipleOccurrencePlaceholders()
|
||||
* @see \Drupal\Tests\big_pipe\Functional\BigPipeTest::testBigPipeMultiOccurrencePlaceholders()
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
@@ -134,7 +133,7 @@ class BigPipeTestController {
|
||||
/**
|
||||
* #lazy_builder callback; returns the current count.
|
||||
*
|
||||
* @see \Drupal\big_pipe\Tests\BigPipeTest::testBigPipeMultipleOccurrencePlaceholders()
|
||||
* @see \Drupal\Tests\big_pipe\Functional\BigPipeTest::testBigPipeMultiOccurrencePlaceholders()
|
||||
*
|
||||
* @return array
|
||||
* The render array.
|
||||
|
||||
@@ -35,6 +35,6 @@ class BigPipeTestForm extends FormBase {
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) { }
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\big_pipe\Functional;
|
||||
|
||||
use Behat\Mink\Element\NodeElement;
|
||||
use Drupal\big_pipe\Render\Placeholder\BigPipeStrategy;
|
||||
use Drupal\big_pipe\Render\BigPipe;
|
||||
use Drupal\big_pipe_test\BigPipePlaceholderTestCases;
|
||||
use Drupal\Component\Serialization\Json;
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Core\Logger\RfcLogLevel;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests BigPipe's no-JS detection & response delivery (with and without JS).
|
||||
*
|
||||
* Covers:
|
||||
* - big_pipe_page_attachments()
|
||||
* - \Drupal\big_pipe\Controller\BigPipeController
|
||||
* - \Drupal\big_pipe\EventSubscriber\HtmlResponseBigPipeSubscriber
|
||||
* - \Drupal\big_pipe\Render\BigPipe
|
||||
*
|
||||
* @group big_pipe
|
||||
*/
|
||||
class BigPipeTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['big_pipe', 'big_pipe_test', 'dblog'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $dumpHeaders = TRUE;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Ignore the <meta> refresh that big_pipe.module sets. It causes a redirect
|
||||
// to a page that sets another cookie, which causes WebTestBase to lose the
|
||||
// session cookie. To avoid this problem, tests should first call
|
||||
// drupalGet() and then call checkForMetaRefresh() manually, and then reset
|
||||
// $this->maximumMetaRefreshCount and $this->metaRefreshCount.
|
||||
// @see doMetaRefresh()
|
||||
$this->maximumMetaRefreshCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a single <meta> refresh explicitly.
|
||||
*
|
||||
* This test disables the automatic <meta> refresh checking, each time it is
|
||||
* desired that this runs, a test case must explicitly call this.
|
||||
*
|
||||
* @see setUp()
|
||||
*/
|
||||
protected function performMetaRefresh() {
|
||||
$this->maximumMetaRefreshCount = 1;
|
||||
$this->checkForMetaRefresh();
|
||||
$this->maximumMetaRefreshCount = 0;
|
||||
$this->metaRefreshCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests BigPipe's no-JS detection.
|
||||
*
|
||||
* Covers:
|
||||
* - big_pipe_page_attachments()
|
||||
* - \Drupal\big_pipe\Controller\BigPipeController
|
||||
*/
|
||||
public function testNoJsDetection() {
|
||||
$no_js_to_js_markup = '<script>document.cookie = "' . BigPipeStrategy::NOJS_COOKIE . '=1; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"</script>';
|
||||
|
||||
// 1. No session (anonymous).
|
||||
$this->drupalGet(Url::fromRoute('<front>'));
|
||||
$this->assertSessionCookieExists(FALSE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
$this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
|
||||
$this->assertNoRaw($no_js_to_js_markup);
|
||||
|
||||
// 2. Session (authenticated).
|
||||
$this->drupalLogin($this->rootUser);
|
||||
$this->assertSessionCookieExists(TRUE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
$this->assertRaw('<noscript><meta http-equiv="Refresh" content="0; URL=' . base_path() . 'big_pipe/no-js?destination=' . base_path() . 'user/1" />' . "\n" . '</noscript>');
|
||||
$this->assertNoRaw($no_js_to_js_markup);
|
||||
$this->assertBigPipeNoJsMetaRefreshRedirect();
|
||||
$this->assertBigPipeNoJsCookieExists(TRUE);
|
||||
$this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
|
||||
$this->assertRaw($no_js_to_js_markup);
|
||||
$this->drupalLogout();
|
||||
|
||||
// Close the prior connection and remove the collected state.
|
||||
$this->getSession()->reset();
|
||||
|
||||
// 3. Session (anonymous).
|
||||
$this->drupalGet(Url::fromRoute('user.login', [], ['query' => ['trigger_session' => 1]]));
|
||||
$this->drupalGet(Url::fromRoute('user.login'));
|
||||
$this->assertSessionCookieExists(TRUE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
$this->assertRaw('<noscript><meta http-equiv="Refresh" content="0; URL=' . base_path() . 'big_pipe/no-js?destination=' . base_path() . 'user/login" />' . "\n" . '</noscript>');
|
||||
$this->assertNoRaw($no_js_to_js_markup);
|
||||
$this->assertBigPipeNoJsMetaRefreshRedirect();
|
||||
$this->assertBigPipeNoJsCookieExists(TRUE);
|
||||
$this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
|
||||
$this->assertRaw($no_js_to_js_markup);
|
||||
|
||||
// Close the prior connection and remove the collected state.
|
||||
$this->getSession()->reset();
|
||||
|
||||
// Edge case: route with '_no_big_pipe' option.
|
||||
$this->drupalGet(Url::fromRoute('no_big_pipe'));
|
||||
$this->assertSessionCookieExists(FALSE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
$this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
|
||||
$this->assertNoRaw($no_js_to_js_markup);
|
||||
$this->drupalLogin($this->rootUser);
|
||||
$this->drupalGet(Url::fromRoute('no_big_pipe'));
|
||||
$this->assertSessionCookieExists(TRUE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
$this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=');
|
||||
$this->assertNoRaw($no_js_to_js_markup);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests BigPipe-delivered HTML responses when JavaScript is enabled.
|
||||
*
|
||||
* Covers:
|
||||
* - \Drupal\big_pipe\EventSubscriber\HtmlResponseBigPipeSubscriber
|
||||
* - \Drupal\big_pipe\Render\BigPipe
|
||||
* - \Drupal\big_pipe\Render\BigPipe::sendPlaceholders()
|
||||
*
|
||||
* @see \Drupal\big_pipe_test\BigPipePlaceholderTestCases
|
||||
*/
|
||||
public function testBigPipe() {
|
||||
// Simulate production.
|
||||
$this->config('system.logging')->set('error_level', ERROR_REPORTING_HIDE)->save();
|
||||
|
||||
$this->drupalLogin($this->rootUser);
|
||||
$this->assertSessionCookieExists(TRUE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
|
||||
$log_count = db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField();
|
||||
|
||||
// By not calling performMetaRefresh() here, we simulate JavaScript being
|
||||
// enabled, because as far as the BigPipe module is concerned, JavaScript is
|
||||
// enabled in the browser as long as the BigPipe no-JS cookie is *not* set.
|
||||
// @see setUp()
|
||||
// @see performMetaRefresh()
|
||||
|
||||
$this->drupalGet(Url::fromRoute('big_pipe_test'));
|
||||
$this->assertBigPipeResponseHeadersPresent();
|
||||
$this->assertNoCacheTag('cache_tag_set_in_lazy_builder');
|
||||
|
||||
$this->setCsrfTokenSeedInTestEnvironment();
|
||||
$cases = $this->getTestCases();
|
||||
$this->assertBigPipeNoJsPlaceholders([
|
||||
$cases['edge_case__invalid_html']->bigPipeNoJsPlaceholder => $cases['edge_case__invalid_html']->embeddedHtmlResponse,
|
||||
$cases['html_attribute_value']->bigPipeNoJsPlaceholder => $cases['html_attribute_value']->embeddedHtmlResponse,
|
||||
$cases['html_attribute_value_subset']->bigPipeNoJsPlaceholder => $cases['html_attribute_value_subset']->embeddedHtmlResponse,
|
||||
]);
|
||||
$this->assertBigPipePlaceholders([
|
||||
$cases['html']->bigPipePlaceholderId => Json::encode($cases['html']->embeddedAjaxResponseCommands),
|
||||
$cases['edge_case__html_non_lazy_builder']->bigPipePlaceholderId => Json::encode($cases['edge_case__html_non_lazy_builder']->embeddedAjaxResponseCommands),
|
||||
$cases['exception__lazy_builder']->bigPipePlaceholderId => NULL,
|
||||
$cases['exception__embedded_response']->bigPipePlaceholderId => NULL,
|
||||
], [
|
||||
0 => $cases['edge_case__html_non_lazy_builder']->bigPipePlaceholderId,
|
||||
// The 'html' case contains the 'status messages' placeholder, which is
|
||||
// always rendered last.
|
||||
1 => $cases['html']->bigPipePlaceholderId,
|
||||
]);
|
||||
|
||||
$this->assertRaw('</body>', 'Closing body tag present.');
|
||||
|
||||
$this->pass('Verifying BigPipe assets are present…', 'Debug');
|
||||
$this->assertFalse(empty($this->getDrupalSettings()), 'drupalSettings present.');
|
||||
$this->assertTrue(in_array('big_pipe/big_pipe', explode(',', $this->getDrupalSettings()['ajaxPageState']['libraries'])), 'BigPipe asset library is present.');
|
||||
|
||||
// Verify that the two expected exceptions are logged as errors.
|
||||
$this->assertEqual($log_count + 2, db_query('SELECT COUNT(*) FROM {watchdog}')->fetchField(), 'Two new watchdog entries.');
|
||||
$records = db_query('SELECT * FROM {watchdog} ORDER BY wid DESC LIMIT 2')->fetchAll();
|
||||
$this->assertEqual(RfcLogLevel::ERROR, $records[0]->severity);
|
||||
$this->assertTrue(FALSE !== strpos((string) unserialize($records[0]->variables)['@message'], 'Oh noes!'));
|
||||
$this->assertEqual(RfcLogLevel::ERROR, $records[1]->severity);
|
||||
$this->assertTrue(FALSE !== strpos((string) unserialize($records[1]->variables)['@message'], 'You are not allowed to say llamas are not cool!'));
|
||||
|
||||
// Verify that 4xx responses work fine. (4xx responses are handled by
|
||||
// subrequests to a route pointing to a controller with the desired output.)
|
||||
$this->drupalGet(Url::fromUri('base:non-existing-path'));
|
||||
|
||||
// Simulate development.
|
||||
$this->pass('Verifying BigPipe provides useful error output when an error occurs while rendering a placeholder if verbose error logging is enabled.', 'Debug');
|
||||
$this->config('system.logging')->set('error_level', ERROR_REPORTING_DISPLAY_VERBOSE)->save();
|
||||
$this->drupalGet(Url::fromRoute('big_pipe_test'));
|
||||
// The 'edge_case__html_exception' case throws an exception.
|
||||
$this->assertRaw('The website encountered an unexpected error. Please try again later');
|
||||
$this->assertRaw('You are not allowed to say llamas are not cool!');
|
||||
$this->assertNoRaw(BigPipe::STOP_SIGNAL, 'BigPipe stop signal absent: error occurred before then.');
|
||||
$this->assertNoRaw('</body>', 'Closing body tag absent: error occurred before then.');
|
||||
// The exception is expected. Do not interpret it as a test failure.
|
||||
unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests BigPipe-delivered HTML responses when JavaScript is disabled.
|
||||
*
|
||||
* Covers:
|
||||
* - \Drupal\big_pipe\EventSubscriber\HtmlResponseBigPipeSubscriber
|
||||
* - \Drupal\big_pipe\Render\BigPipe
|
||||
* - \Drupal\big_pipe\Render\BigPipe::sendNoJsPlaceholders()
|
||||
*
|
||||
* @see \Drupal\big_pipe_test\BigPipePlaceholderTestCases
|
||||
*/
|
||||
public function testBigPipeNoJs() {
|
||||
// Simulate production.
|
||||
$this->config('system.logging')->set('error_level', ERROR_REPORTING_HIDE)->save();
|
||||
|
||||
$this->drupalLogin($this->rootUser);
|
||||
$this->assertSessionCookieExists(TRUE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
|
||||
// By calling performMetaRefresh() here, we simulate JavaScript being
|
||||
// disabled, because as far as the BigPipe module is concerned, it is
|
||||
// enabled in the browser when the BigPipe no-JS cookie is set.
|
||||
// @see setUp()
|
||||
// @see performMetaRefresh()
|
||||
$this->performMetaRefresh();
|
||||
$this->assertBigPipeNoJsCookieExists(TRUE);
|
||||
|
||||
$this->drupalGet(Url::fromRoute('big_pipe_test'));
|
||||
$this->assertBigPipeResponseHeadersPresent();
|
||||
$this->assertNoCacheTag('cache_tag_set_in_lazy_builder');
|
||||
|
||||
$this->setCsrfTokenSeedInTestEnvironment();
|
||||
$cases = $this->getTestCases();
|
||||
$this->assertBigPipeNoJsPlaceholders([
|
||||
$cases['edge_case__invalid_html']->bigPipeNoJsPlaceholder => $cases['edge_case__invalid_html']->embeddedHtmlResponse,
|
||||
$cases['html_attribute_value']->bigPipeNoJsPlaceholder => $cases['html_attribute_value']->embeddedHtmlResponse,
|
||||
$cases['html_attribute_value_subset']->bigPipeNoJsPlaceholder => $cases['html_attribute_value_subset']->embeddedHtmlResponse,
|
||||
$cases['html']->bigPipeNoJsPlaceholder => $cases['html']->embeddedHtmlResponse,
|
||||
$cases['edge_case__html_non_lazy_builder']->bigPipeNoJsPlaceholder => $cases['edge_case__html_non_lazy_builder']->embeddedHtmlResponse,
|
||||
$cases['exception__lazy_builder']->bigPipePlaceholderId => NULL,
|
||||
$cases['exception__embedded_response']->bigPipePlaceholderId => NULL,
|
||||
]);
|
||||
|
||||
$this->pass('Verifying there are no BigPipe placeholders & replacements…', 'Debug');
|
||||
$this->assertEqual('<none>', $this->drupalGetHeader('BigPipe-Test-Placeholders'));
|
||||
$this->pass('Verifying BigPipe start/stop signals are absent…', 'Debug');
|
||||
$this->assertNoRaw(BigPipe::START_SIGNAL, 'BigPipe start signal absent.');
|
||||
$this->assertNoRaw(BigPipe::STOP_SIGNAL, 'BigPipe stop signal absent.');
|
||||
|
||||
$this->pass('Verifying BigPipe assets are absent…', 'Debug');
|
||||
$this->assertTrue(!isset($this->getDrupalSettings()['bigPipePlaceholderIds']) && empty($this->getDrupalSettings()['ajaxPageState']), 'BigPipe drupalSettings and BigPipe asset library absent.');
|
||||
$this->assertRaw('</body>', 'Closing body tag present.');
|
||||
|
||||
// Verify that 4xx responses work fine. (4xx responses are handled by
|
||||
// subrequests to a route pointing to a controller with the desired output.)
|
||||
$this->drupalGet(Url::fromUri('base:non-existing-path'));
|
||||
|
||||
// Simulate development.
|
||||
$this->pass('Verifying BigPipe provides useful error output when an error occurs while rendering a placeholder if verbose error logging is enabled.', 'Debug');
|
||||
$this->config('system.logging')->set('error_level', ERROR_REPORTING_DISPLAY_VERBOSE)->save();
|
||||
$this->drupalGet(Url::fromRoute('big_pipe_test'));
|
||||
// The 'edge_case__html_exception' case throws an exception.
|
||||
$this->assertRaw('The website encountered an unexpected error. Please try again later');
|
||||
$this->assertRaw('You are not allowed to say llamas are not cool!');
|
||||
$this->assertNoRaw('</body>', 'Closing body tag absent: error occurred before then.');
|
||||
// The exception is expected. Do not interpret it as a test failure.
|
||||
unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests BigPipe with a multi-occurrence placeholder.
|
||||
*/
|
||||
public function testBigPipeMultiOccurrencePlaceholders() {
|
||||
$this->drupalLogin($this->rootUser);
|
||||
$this->assertSessionCookieExists(TRUE);
|
||||
$this->assertBigPipeNoJsCookieExists(FALSE);
|
||||
|
||||
// By not calling performMetaRefresh() here, we simulate JavaScript being
|
||||
// enabled, because as far as the BigPipe module is concerned, JavaScript is
|
||||
// enabled in the browser as long as the BigPipe no-JS cookie is *not* set.
|
||||
// @see setUp()
|
||||
// @see performMetaRefresh()
|
||||
|
||||
$this->drupalGet(Url::fromRoute('big_pipe_test_multi_occurrence'));
|
||||
$big_pipe_placeholder_id = 'callback=Drupal%5CCore%5CRender%5CElement%5CStatusMessages%3A%3ArenderMessages&args%5B0%5D&token=_HAdUpwWmet0TOTe2PSiJuMntExoshbm1kh2wQzzzAA';
|
||||
$expected_placeholder_replacement = '<script type="application/vnd.drupal-ajax" data-big-pipe-replacement-for-placeholder-with-id="' . $big_pipe_placeholder_id . '">';
|
||||
$this->assertRaw('The count is 1.');
|
||||
$this->assertNoRaw('The count is 2.');
|
||||
$this->assertNoRaw('The count is 3.');
|
||||
$raw_content = $this->getRawContent();
|
||||
$this->assertTrue(substr_count($raw_content, $expected_placeholder_replacement) == 1, 'Only one placeholder replacement was found for the duplicate #lazy_builder arrays.');
|
||||
|
||||
// By calling performMetaRefresh() here, we simulate JavaScript being
|
||||
// disabled, because as far as the BigPipe module is concerned, it is
|
||||
// enabled in the browser when the BigPipe no-JS cookie is set.
|
||||
// @see setUp()
|
||||
// @see performMetaRefresh()
|
||||
$this->performMetaRefresh();
|
||||
$this->assertBigPipeNoJsCookieExists(TRUE);
|
||||
$this->drupalGet(Url::fromRoute('big_pipe_test_multi_occurrence'));
|
||||
$this->assertRaw('The count is 1.');
|
||||
$this->assertNoRaw('The count is 2.');
|
||||
$this->assertNoRaw('The count is 3.');
|
||||
}
|
||||
|
||||
protected function assertBigPipeResponseHeadersPresent() {
|
||||
$this->pass('Verifying BigPipe response headers…', 'Debug');
|
||||
$this->assertTrue(FALSE !== strpos($this->drupalGetHeader('Cache-Control'), 'private'), 'Cache-Control header set to "private".');
|
||||
$this->assertEqual('no-store, content="BigPipe/1.0"', $this->drupalGetHeader('Surrogate-Control'));
|
||||
$this->assertEqual('no', $this->drupalGetHeader('X-Accel-Buffering'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts expected BigPipe no-JS placeholders are present and replaced.
|
||||
*
|
||||
* @param array $expected_big_pipe_nojs_placeholders
|
||||
* Keys: BigPipe no-JS placeholder markup. Values: expected replacement
|
||||
* markup.
|
||||
*/
|
||||
protected function assertBigPipeNoJsPlaceholders(array $expected_big_pipe_nojs_placeholders) {
|
||||
$this->pass('Verifying BigPipe no-JS placeholders & replacements…', 'Debug');
|
||||
$this->assertSetsEqual(array_keys($expected_big_pipe_nojs_placeholders), array_map('rawurldecode', explode(' ', $this->drupalGetHeader('BigPipe-Test-No-Js-Placeholders'))));
|
||||
foreach ($expected_big_pipe_nojs_placeholders as $big_pipe_nojs_placeholder => $expected_replacement) {
|
||||
$this->pass('Checking whether the replacement for the BigPipe no-JS placeholder "' . $big_pipe_nojs_placeholder . '" is present:');
|
||||
$this->assertNoRaw($big_pipe_nojs_placeholder);
|
||||
if ($expected_replacement !== NULL) {
|
||||
$this->assertRaw($expected_replacement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts expected BigPipe placeholders are present and replaced.
|
||||
*
|
||||
* @param array $expected_big_pipe_placeholders
|
||||
* Keys: BigPipe placeholder IDs. Values: expected AJAX response.
|
||||
* @param array $expected_big_pipe_placeholder_stream_order
|
||||
* Keys: BigPipe placeholder IDs. Values: expected AJAX response. Keys are
|
||||
* defined in the order that they are expected to be rendered & streamed.
|
||||
*/
|
||||
protected function assertBigPipePlaceholders(array $expected_big_pipe_placeholders, array $expected_big_pipe_placeholder_stream_order) {
|
||||
$this->pass('Verifying BigPipe placeholders & replacements…', 'Debug');
|
||||
$this->assertSetsEqual(array_keys($expected_big_pipe_placeholders), explode(' ', $this->drupalGetHeader('BigPipe-Test-Placeholders')));
|
||||
$placeholder_positions = [];
|
||||
$placeholder_replacement_positions = [];
|
||||
foreach ($expected_big_pipe_placeholders as $big_pipe_placeholder_id => $expected_ajax_response) {
|
||||
$this->pass('BigPipe placeholder: ' . $big_pipe_placeholder_id, 'Debug');
|
||||
// Verify expected placeholder.
|
||||
$expected_placeholder_html = '<span data-big-pipe-placeholder-id="' . $big_pipe_placeholder_id . '"></span>';
|
||||
$this->assertRaw($expected_placeholder_html, 'BigPipe placeholder for placeholder ID "' . $big_pipe_placeholder_id . '" found.');
|
||||
$pos = strpos($this->getRawContent(), $expected_placeholder_html);
|
||||
$placeholder_positions[$pos] = $big_pipe_placeholder_id;
|
||||
// Verify expected placeholder replacement.
|
||||
$expected_placeholder_replacement = '<script type="application/vnd.drupal-ajax" data-big-pipe-replacement-for-placeholder-with-id="' . $big_pipe_placeholder_id . '">';
|
||||
$result = $this->xpath('//script[@data-big-pipe-replacement-for-placeholder-with-id=:id]', [':id' => Html::decodeEntities($big_pipe_placeholder_id)]);
|
||||
if ($expected_ajax_response === NULL) {
|
||||
$this->assertEqual(0, count($result));
|
||||
$this->assertNoRaw($expected_placeholder_replacement);
|
||||
continue;
|
||||
}
|
||||
$this->assertEqual($expected_ajax_response, trim($result[0]->getText()));
|
||||
$this->assertRaw($expected_placeholder_replacement);
|
||||
$pos = strpos($this->getRawContent(), $expected_placeholder_replacement);
|
||||
$placeholder_replacement_positions[$pos] = $big_pipe_placeholder_id;
|
||||
}
|
||||
ksort($placeholder_positions, SORT_NUMERIC);
|
||||
$this->assertEqual(array_keys($expected_big_pipe_placeholders), array_values($placeholder_positions));
|
||||
$placeholders = array_map(function (NodeElement $element) {
|
||||
return $element->getAttribute('data-big-pipe-placeholder-id');
|
||||
}, $this->cssSelect('[data-big-pipe-placeholder-id]'));
|
||||
$this->assertEqual(count($expected_big_pipe_placeholders), count(array_unique($placeholders)));
|
||||
$expected_big_pipe_placeholders_with_replacements = [];
|
||||
foreach ($expected_big_pipe_placeholder_stream_order as $big_pipe_placeholder_id) {
|
||||
$expected_big_pipe_placeholders_with_replacements[$big_pipe_placeholder_id] = $expected_big_pipe_placeholders[$big_pipe_placeholder_id];
|
||||
}
|
||||
$this->assertEqual($expected_big_pipe_placeholders_with_replacements, array_filter($expected_big_pipe_placeholders));
|
||||
$this->assertSetsEqual(array_keys($expected_big_pipe_placeholders_with_replacements), array_values($placeholder_replacement_positions));
|
||||
$this->assertEqual(count($expected_big_pipe_placeholders_with_replacements), preg_match_all('/' . preg_quote('<script type="application/vnd.drupal-ajax" data-big-pipe-replacement-for-placeholder-with-id="', '/') . '/', $this->getRawContent()));
|
||||
|
||||
$this->pass('Verifying BigPipe start/stop signals…', 'Debug');
|
||||
$this->assertRaw(BigPipe::START_SIGNAL, 'BigPipe start signal present.');
|
||||
$this->assertRaw(BigPipe::STOP_SIGNAL, 'BigPipe stop signal present.');
|
||||
$start_signal_position = strpos($this->getRawContent(), BigPipe::START_SIGNAL);
|
||||
$stop_signal_position = strpos($this->getRawContent(), BigPipe::STOP_SIGNAL);
|
||||
$this->assertTrue($start_signal_position < $stop_signal_position, 'BigPipe start signal appears before stop signal.');
|
||||
|
||||
$this->pass('Verifying BigPipe placeholder replacements and start/stop signals were streamed in the correct order…', 'Debug');
|
||||
$expected_stream_order = array_keys($expected_big_pipe_placeholders_with_replacements);
|
||||
array_unshift($expected_stream_order, BigPipe::START_SIGNAL);
|
||||
array_push($expected_stream_order, BigPipe::STOP_SIGNAL);
|
||||
$actual_stream_order = $placeholder_replacement_positions + [
|
||||
$start_signal_position => BigPipe::START_SIGNAL,
|
||||
$stop_signal_position => BigPipe::STOP_SIGNAL,
|
||||
];
|
||||
ksort($actual_stream_order, SORT_NUMERIC);
|
||||
$this->assertEqual($expected_stream_order, array_values($actual_stream_order));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures CSRF tokens can be generated for the current user's session.
|
||||
*/
|
||||
protected function setCsrfTokenSeedInTestEnvironment() {
|
||||
$session_data = $this->container->get('session_handler.write_safe')->read($this->getSession()->getCookie($this->getSessionName()));
|
||||
$csrf_token_seed = unserialize(explode('_sf2_meta|', $session_data)[1])['s'];
|
||||
$this->container->get('session_manager.metadata_bag')->setCsrfTokenSeed($csrf_token_seed);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Drupal\big_pipe_test\BigPipePlaceholderTestCase[]
|
||||
*/
|
||||
protected function getTestCases($has_session = TRUE) {
|
||||
return BigPipePlaceholderTestCases::cases($this->container, $this->rootUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts whether arrays A and B are equal, when treated as sets.
|
||||
*/
|
||||
protected function assertSetsEqual(array $a, array $b) {
|
||||
return count($a) == count($b) && !array_diff_assoc($a, $b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts whether a BigPipe no-JS cookie exists or not.
|
||||
*/
|
||||
protected function assertBigPipeNoJsCookieExists($expected) {
|
||||
$this->assertCookieExists('big_pipe_nojs', $expected, 'BigPipe no-JS');
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts whether a session cookie exists or not.
|
||||
*/
|
||||
protected function assertSessionCookieExists($expected) {
|
||||
$this->assertCookieExists($this->getSessionName(), $expected, 'Session');
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts whether a cookie exists on the client or not.
|
||||
*/
|
||||
protected function assertCookieExists($cookie_name, $expected, $cookie_label) {
|
||||
$this->assertEqual($expected, !empty($this->getSession()->getCookie($cookie_name)), $expected ? "$cookie_label cookie exists." : "$cookie_label cookie does not exist.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls ::performMetaRefresh() and asserts the responses.
|
||||
*/
|
||||
protected function assertBigPipeNoJsMetaRefreshRedirect() {
|
||||
$original_url = $this->getSession()->getCurrentUrl();
|
||||
|
||||
// Disable automatic following of redirects by the HTTP client, so that this
|
||||
// test can analyze the response headers of each redirect response.
|
||||
$this->getSession()->getDriver()->getClient()->followRedirects(FALSE);
|
||||
$this->performMetaRefresh();
|
||||
$headers[0] = $this->getSession()->getResponseHeaders();
|
||||
$statuses[0] = $this->getSession()->getStatusCode();
|
||||
$this->performMetaRefresh();
|
||||
$headers[1] = $this->getSession()->getResponseHeaders();
|
||||
$statuses[1] = $this->getSession()->getStatusCode();
|
||||
$this->getSession()->getDriver()->getClient()->followRedirects(TRUE);
|
||||
|
||||
$this->assertEqual($original_url, $this->getSession()->getCurrentUrl(), 'Redirected back to the original location.');
|
||||
|
||||
// First response: redirect.
|
||||
$this->assertEqual(302, $statuses[0], 'The first response was a 302 (redirect).');
|
||||
$this->assertIdentical(0, strpos($headers[0]['Set-Cookie'][0], 'big_pipe_nojs=1'), 'The first response sets the big_pipe_nojs cookie.');
|
||||
$this->assertEqual($original_url, $headers[0]['Location'][0], 'The first response redirected back to the original page.');
|
||||
$this->assertTrue(empty(array_diff(['cookies:big_pipe_nojs', 'session.exists'], explode(' ', $headers[0]['X-Drupal-Cache-Contexts'][0]))), 'The first response varies by the "cookies:big_pipe_nojs" and "session.exists" cache contexts.');
|
||||
$this->assertFalse(isset($headers[0]['Surrogate-Control']), 'The first response has no "Surrogate-Control" header.');
|
||||
|
||||
// Second response: redirect followed.
|
||||
$this->assertEqual(200, $statuses[1], 'The second response was a 200.');
|
||||
$this->assertTrue(empty(array_diff(['cookies:big_pipe_nojs', 'session.exists'], explode(' ', $headers[0]['X-Drupal-Cache-Contexts'][0]))), 'The first response varies by the "cookies:big_pipe_nojs" and "session.exists" cache contexts.');
|
||||
$this->assertEqual('no-store, content="BigPipe/1.0"', $headers[1]['Surrogate-Control'][0], 'The second response has a "Surrogate-Control" header.');
|
||||
|
||||
$this->assertNoRaw('<noscript><meta http-equiv="Refresh" content="0; URL=', 'Once the BigPipe no-JS cookie is set, the <meta> refresh is absent: only one redirect ever happens.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace Drupal\Tests\big_pipe\Unit\Render\Placeholder;
|
||||
|
||||
use Drupal\big_pipe\Render\Placeholder\BigPipeStrategy;
|
||||
use Drupal\big_pipe\Tests\BigPipePlaceholderTestCases;
|
||||
use Drupal\big_pipe_test\BigPipePlaceholderTestCases;
|
||||
use Drupal\Core\Routing\RouteMatchInterface;
|
||||
use Drupal\Core\Session\SessionConfigurationInterface;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
@@ -47,7 +47,7 @@ class BigPipeStrategyTest extends UnitTestCase {
|
||||
$big_pipe_strategy = new BigPipeStrategy($session_configuration->reveal(), $request_stack->reveal(), $route_match->reveal());
|
||||
$processed_placeholders = $big_pipe_strategy->processPlaceholders($placeholders);
|
||||
|
||||
if ($request->isMethodSafe() && !$route_match_has_no_big_pipe_option && $request_has_session) {
|
||||
if ($request->isMethodCacheable() && !$route_match_has_no_big_pipe_option && $request_has_session) {
|
||||
$this->assertSameSize($expected_big_pipe_placeholders, $processed_placeholders, 'BigPipe is able to deliver all placeholders.');
|
||||
foreach (array_keys($placeholders) as $placeholder) {
|
||||
$this->assertSame($expected_big_pipe_placeholders[$placeholder], $processed_placeholders[$placeholder], "Verifying how BigPipeStrategy handles the placeholder '$placeholder'");
|
||||
@@ -59,7 +59,7 @@ class BigPipeStrategyTest extends UnitTestCase {
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Drupal\big_pipe\Tests\BigPipePlaceholderTestCases
|
||||
* @see \Drupal\big_pipe_test\BigPipePlaceholderTestCases
|
||||
*/
|
||||
public function placeholdersProvider() {
|
||||
$cases = BigPipePlaceholderTestCases::cases();
|
||||
@@ -83,25 +83,29 @@ class BigPipeStrategyTest extends UnitTestCase {
|
||||
'_no_big_pipe present, no session, no-JS cookie present' => [$placeholders, 'GET', TRUE, FALSE, TRUE, []],
|
||||
'_no_big_pipe present, session, no-JS cookie absent' => [$placeholders, 'GET', TRUE, TRUE, FALSE, []],
|
||||
'_no_big_pipe present, session, no-JS cookie present' => [$placeholders, 'GET', TRUE, TRUE, TRUE, []],
|
||||
'_no_big_pipe absent, session, no-JS cookie absent: (JS-powered) BigPipe placeholder used for HTML placeholders' => [$placeholders, 'GET', FALSE, TRUE, FALSE, [
|
||||
$cases['html']->placeholder => $cases['html']->bigPipePlaceholderRenderArray,
|
||||
$cases['html_attribute_value']->placeholder => $cases['html_attribute_value']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['html_attribute_value_subset']->placeholder => $cases['html_attribute_value_subset']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__invalid_html']->placeholder => $cases['edge_case__invalid_html']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__html_non_lazy_builder']->placeholder => $cases['edge_case__html_non_lazy_builder']->bigPipePlaceholderRenderArray,
|
||||
$cases['exception__lazy_builder']->placeholder => $cases['exception__lazy_builder']->bigPipePlaceholderRenderArray,
|
||||
$cases['exception__embedded_response']->placeholder => $cases['exception__embedded_response']->bigPipePlaceholderRenderArray,
|
||||
]],
|
||||
'_no_big_pipe absent, session, no-JS cookie absent: (JS-powered) BigPipe placeholder used for HTML placeholders' => [
|
||||
$placeholders, 'GET', FALSE, TRUE, FALSE, [
|
||||
$cases['html']->placeholder => $cases['html']->bigPipePlaceholderRenderArray,
|
||||
$cases['html_attribute_value']->placeholder => $cases['html_attribute_value']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['html_attribute_value_subset']->placeholder => $cases['html_attribute_value_subset']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__invalid_html']->placeholder => $cases['edge_case__invalid_html']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__html_non_lazy_builder']->placeholder => $cases['edge_case__html_non_lazy_builder']->bigPipePlaceholderRenderArray,
|
||||
$cases['exception__lazy_builder']->placeholder => $cases['exception__lazy_builder']->bigPipePlaceholderRenderArray,
|
||||
$cases['exception__embedded_response']->placeholder => $cases['exception__embedded_response']->bigPipePlaceholderRenderArray,
|
||||
],
|
||||
],
|
||||
'_no_big_pipe absent, session, no-JS cookie absent: (JS-powered) BigPipe placeholder used for HTML placeholders — but unsafe method' => [$placeholders, 'POST', FALSE, TRUE, FALSE, []],
|
||||
'_no_big_pipe absent, session, no-JS cookie present: no-JS BigPipe placeholder used for HTML placeholders' => [$placeholders, 'GET', FALSE, TRUE, TRUE, [
|
||||
$cases['html']->placeholder => $cases['html']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['html_attribute_value']->placeholder => $cases['html_attribute_value']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['html_attribute_value_subset']->placeholder => $cases['html_attribute_value_subset']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__invalid_html']->placeholder => $cases['edge_case__invalid_html']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__html_non_lazy_builder']->placeholder => $cases['edge_case__html_non_lazy_builder']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['exception__lazy_builder']->placeholder => $cases['exception__lazy_builder']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['exception__embedded_response']->placeholder => $cases['exception__embedded_response']->bigPipeNoJsPlaceholderRenderArray,
|
||||
]],
|
||||
'_no_big_pipe absent, session, no-JS cookie present: no-JS BigPipe placeholder used for HTML placeholders' => [
|
||||
$placeholders, 'GET', FALSE, TRUE, TRUE, [
|
||||
$cases['html']->placeholder => $cases['html']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['html_attribute_value']->placeholder => $cases['html_attribute_value']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['html_attribute_value_subset']->placeholder => $cases['html_attribute_value_subset']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__invalid_html']->placeholder => $cases['edge_case__invalid_html']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['edge_case__html_non_lazy_builder']->placeholder => $cases['edge_case__html_non_lazy_builder']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['exception__lazy_builder']->placeholder => $cases['exception__lazy_builder']->bigPipeNoJsPlaceholderRenderArray,
|
||||
$cases['exception__embedded_response']->placeholder => $cases['exception__embedded_response']->bigPipeNoJsPlaceholderRenderArray,
|
||||
],
|
||||
],
|
||||
'_no_big_pipe absent, session, no-JS cookie present: no-JS BigPipe placeholder used for HTML placeholders — but unsafe method' => [$placeholders, 'POST', FALSE, TRUE, TRUE, []],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ description: 'Theme for testing BigPipe edge cases.'
|
||||
# version: VERSION
|
||||
# core: 8.x
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -6,8 +6,8 @@ package: Core
|
||||
# core: 8.x
|
||||
configure: block.admin_display
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -16,4 +16,6 @@ drupal.block.admin:
|
||||
dependencies:
|
||||
- core/jquery
|
||||
- core/drupal
|
||||
- core/drupal.announce
|
||||
- core/drupal.debounce
|
||||
- core/drupal.dialog.ajax
|
||||
|
||||
@@ -52,7 +52,7 @@ block.admin_display:
|
||||
_permission: 'administer blocks'
|
||||
|
||||
block.admin_display_theme:
|
||||
path: 'admin/structure/block/list/{theme}'
|
||||
path: '/admin/structure/block/list/{theme}'
|
||||
defaults:
|
||||
_controller: '\Drupal\block\Controller\BlockListController::listing'
|
||||
_title: 'Block layout'
|
||||
@@ -61,7 +61,7 @@ block.admin_display_theme:
|
||||
_permission: 'administer blocks'
|
||||
|
||||
block.admin_library:
|
||||
path: 'admin/structure/block/library/{theme}'
|
||||
path: '/admin/structure/block/library/{theme}'
|
||||
defaults:
|
||||
_controller: '\Drupal\block\Controller\BlockLibraryController::listBlocks'
|
||||
_title: 'Place block'
|
||||
|
||||
@@ -24,7 +24,7 @@ a.block-demo-backlink:visited {
|
||||
font-family: "Lucida Grande", Verdana, sans-serif;
|
||||
font-size: small;
|
||||
line-height: 20px;
|
||||
left: 20px; /*LTR*/
|
||||
left: 20px; /* LTR */
|
||||
padding: 5px 10px;
|
||||
position: fixed;
|
||||
z-index: 499;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* @file
|
||||
* Block admin behaviors.
|
||||
*/
|
||||
|
||||
(function ($, Drupal, debounce) {
|
||||
/**
|
||||
* Filters the block list by a text input search string.
|
||||
*
|
||||
* The text input will have the selector `input.block-filter-text`.
|
||||
*
|
||||
* The target element to do searching in will be in the selector
|
||||
* `input.block-filter-text[data-element]`
|
||||
*
|
||||
* The text source where the text should be found will have the selector
|
||||
* `.block-filter-text-source`
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the behavior for the block filtering.
|
||||
*/
|
||||
Drupal.behaviors.blockFilterByText = {
|
||||
attach(context, settings) {
|
||||
const $input = $('input.block-filter-text').once('block-filter-text');
|
||||
const $table = $($input.attr('data-element'));
|
||||
let $filter_rows;
|
||||
|
||||
/**
|
||||
* Filters the block list.
|
||||
*
|
||||
* @param {jQuery.Event} e
|
||||
* The jQuery event for the keyup event that triggered the filter.
|
||||
*/
|
||||
function filterBlockList(e) {
|
||||
const query = $(e.target).val().toLowerCase();
|
||||
|
||||
/**
|
||||
* Shows or hides the block entry based on the query.
|
||||
*
|
||||
* @param {number} index
|
||||
* The index in the loop, as provided by `jQuery.each`
|
||||
* @param {HTMLElement} label
|
||||
* The label of the block.
|
||||
*/
|
||||
function toggleBlockEntry(index, label) {
|
||||
const $label = $(label);
|
||||
const $row = $label.parent().parent();
|
||||
const textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
|
||||
$row.toggle(textMatch);
|
||||
}
|
||||
|
||||
// Filter if the length of the query is at least 2 characters.
|
||||
if (query.length >= 2) {
|
||||
$filter_rows.each(toggleBlockEntry);
|
||||
Drupal.announce(
|
||||
Drupal.formatPlural(
|
||||
$table.find('tr:visible').length - 1,
|
||||
'1 block is available in the modified list.',
|
||||
'@count blocks are available in the modified list.'
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
$filter_rows.each(function (index) {
|
||||
$(this).parent().parent().show();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if ($table.length) {
|
||||
$filter_rows = $table.find('div.block-filter-text-source');
|
||||
$input.on('keyup', debounce(filterBlockList, 200));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Highlights the block that was just placed into the block listing.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the behavior for the block placement highlighting.
|
||||
*/
|
||||
Drupal.behaviors.blockHighlightPlacement = {
|
||||
attach(context, settings) {
|
||||
if (settings.blockPlacement) {
|
||||
$(context).find('[data-drupal-selector="edit-blocks"]').once('block-highlight').each(function () {
|
||||
const $container = $(this);
|
||||
// Just scrolling the document.body will not work in Firefox. The html
|
||||
// element is needed as well.
|
||||
$('html, body').animate({
|
||||
scrollTop: $('.js-block-placed').offset().top - $container.offset().top + $container.scrollTop(),
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}(jQuery, Drupal, Drupal.debounce));
|
||||
@@ -1,51 +1,20 @@
|
||||
/**
|
||||
* @file
|
||||
* Block admin behaviors.
|
||||
*/
|
||||
* DO NOT EDIT THIS FILE.
|
||||
* See the following change record for more information,
|
||||
* https://www.drupal.org/node/2815083
|
||||
* @preserve
|
||||
**/
|
||||
|
||||
(function ($, Drupal) {
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Filters the block list by a text input search string.
|
||||
*
|
||||
* The text input will have the selector `input.block-filter-text`.
|
||||
*
|
||||
* The target element to do searching in will be in the selector
|
||||
* `input.block-filter-text[data-element]`
|
||||
*
|
||||
* The text source where the text should be found will have the selector
|
||||
* `.block-filter-text-source`
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the behavior for the block filtering.
|
||||
*/
|
||||
(function ($, Drupal, debounce) {
|
||||
Drupal.behaviors.blockFilterByText = {
|
||||
attach: function (context, settings) {
|
||||
attach: function attach(context, settings) {
|
||||
var $input = $('input.block-filter-text').once('block-filter-text');
|
||||
var $table = $($input.attr('data-element'));
|
||||
var $filter_rows;
|
||||
var $filter_rows = void 0;
|
||||
|
||||
/**
|
||||
* Filters the block list.
|
||||
*
|
||||
* @param {jQuery.Event} e
|
||||
* The jQuery event for the keyup event that triggered the filter.
|
||||
*/
|
||||
function filterBlockList(e) {
|
||||
var query = $(e.target).val().toLowerCase();
|
||||
|
||||
/**
|
||||
* Shows or hides the block entry based on the query.
|
||||
*
|
||||
* @param {number} index
|
||||
* The index in the loop, as provided by `jQuery.each`
|
||||
* @param {HTMLElement} label
|
||||
* The label of the block.
|
||||
*/
|
||||
function toggleBlockEntry(index, label) {
|
||||
var $label = $(label);
|
||||
var $row = $label.parent().parent();
|
||||
@@ -53,11 +22,10 @@
|
||||
$row.toggle(textMatch);
|
||||
}
|
||||
|
||||
// Filter if the length of the query is at least 2 characters.
|
||||
if (query.length >= 2) {
|
||||
$filter_rows.each(toggleBlockEntry);
|
||||
}
|
||||
else {
|
||||
Drupal.announce(Drupal.formatPlural($table.find('tr:visible').length - 1, '1 block is available in the modified list.', '@count blocks are available in the modified list.'));
|
||||
} else {
|
||||
$filter_rows.each(function (index) {
|
||||
$(this).parent().parent().show();
|
||||
});
|
||||
@@ -66,26 +34,17 @@
|
||||
|
||||
if ($table.length) {
|
||||
$filter_rows = $table.find('div.block-filter-text-source');
|
||||
$input.on('keyup', filterBlockList);
|
||||
$input.on('keyup', debounce(filterBlockList, 200));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Highlights the block that was just placed into the block listing.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the behavior for the block placement highlighting.
|
||||
*/
|
||||
Drupal.behaviors.blockHighlightPlacement = {
|
||||
attach: function (context, settings) {
|
||||
attach: function attach(context, settings) {
|
||||
if (settings.blockPlacement) {
|
||||
$(context).find('[data-drupal-selector="edit-blocks"]').once('block-highlight').each(function () {
|
||||
var $container = $(this);
|
||||
// Just scrolling the document.body will not work in Firefox. The html
|
||||
// element is needed as well.
|
||||
|
||||
$('html, body').animate({
|
||||
scrollTop: $('.js-block-placed').offset().top - $container.offset().top + $container.scrollTop()
|
||||
}, 500);
|
||||
@@ -93,5 +52,4 @@
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
}(jQuery, Drupal));
|
||||
})(jQuery, Drupal, Drupal.debounce);
|
||||
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* @file
|
||||
* Block behaviors.
|
||||
*/
|
||||
|
||||
(function ($, window, Drupal) {
|
||||
/**
|
||||
* Provide the summary information for the block settings vertical tabs.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the behavior for the block settings summaries.
|
||||
*/
|
||||
Drupal.behaviors.blockSettingsSummary = {
|
||||
attach() {
|
||||
// The drupalSetSummary method required for this behavior is not available
|
||||
// on the Blocks administration page, so we need to make sure this
|
||||
// behavior is processed only if drupalSetSummary is defined.
|
||||
if (typeof $.fn.drupalSetSummary === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a summary for checkboxes in the provided context.
|
||||
*
|
||||
* @param {HTMLDocument|HTMLElement} context
|
||||
* A context where one would find checkboxes to summarize.
|
||||
*
|
||||
* @return {string}
|
||||
* A string with the summary.
|
||||
*/
|
||||
function checkboxesSummary(context) {
|
||||
const vals = [];
|
||||
const $checkboxes = $(context).find('input[type="checkbox"]:checked + label');
|
||||
const il = $checkboxes.length;
|
||||
for (let i = 0; i < il; i++) {
|
||||
vals.push($($checkboxes[i]).html());
|
||||
}
|
||||
if (!vals.length) {
|
||||
vals.push(Drupal.t('Not restricted'));
|
||||
}
|
||||
return vals.join(', ');
|
||||
}
|
||||
|
||||
$('[data-drupal-selector="edit-visibility-node-type"], [data-drupal-selector="edit-visibility-language"], [data-drupal-selector="edit-visibility-user-role"]').drupalSetSummary(checkboxesSummary);
|
||||
|
||||
$('[data-drupal-selector="edit-visibility-request-path"]').drupalSetSummary((context) => {
|
||||
const $pages = $(context).find('textarea[name="visibility[request_path][pages]"]');
|
||||
if (!$pages.val()) {
|
||||
return Drupal.t('Not restricted');
|
||||
}
|
||||
|
||||
return Drupal.t('Restricted to certain pages');
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Move a block in the blocks table between regions via select list.
|
||||
*
|
||||
* This behavior is dependent on the tableDrag behavior, since it uses the
|
||||
* objects initialized in that behavior to update the row.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the tableDrag behaviour for blocks in block administration.
|
||||
*/
|
||||
Drupal.behaviors.blockDrag = {
|
||||
attach(context, settings) {
|
||||
// tableDrag is required and we should be on the blocks admin page.
|
||||
if (typeof Drupal.tableDrag === 'undefined' || typeof Drupal.tableDrag.blocks === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to check empty regions and toggle classes based on this.
|
||||
*
|
||||
* @param {jQuery} table
|
||||
* The jQuery object representing the table to inspect.
|
||||
* @param {jQuery} rowObject
|
||||
* The jQuery object representing the table row.
|
||||
*/
|
||||
function checkEmptyRegions(table, rowObject) {
|
||||
table.find('tr.region-message').each(function () {
|
||||
const $this = $(this);
|
||||
// If the dragged row is in this region, but above the message row,
|
||||
// swap it down one space.
|
||||
if ($this.prev('tr').get(0) === rowObject.element) {
|
||||
// Prevent a recursion problem when using the keyboard to move rows
|
||||
// up.
|
||||
if ((rowObject.method !== 'keyboard' || rowObject.direction === 'down')) {
|
||||
rowObject.swap('after', this);
|
||||
}
|
||||
}
|
||||
// This region has become empty.
|
||||
if ($this.next('tr').is(':not(.draggable)') || $this.next('tr').length === 0) {
|
||||
$this.removeClass('region-populated').addClass('region-empty');
|
||||
}
|
||||
// This region has become populated.
|
||||
else if ($this.is('.region-empty')) {
|
||||
$this.removeClass('region-empty').addClass('region-populated');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to update the last placed row with the correct classes.
|
||||
*
|
||||
* @param {jQuery} table
|
||||
* The jQuery object representing the table to inspect.
|
||||
* @param {jQuery} rowObject
|
||||
* The jQuery object representing the table row.
|
||||
*/
|
||||
function updateLastPlaced(table, rowObject) {
|
||||
// Remove the color-success class from new block if applicable.
|
||||
table.find('.color-success').removeClass('color-success');
|
||||
|
||||
const $rowObject = $(rowObject);
|
||||
if (!$rowObject.is('.drag-previous')) {
|
||||
table.find('.drag-previous').removeClass('drag-previous');
|
||||
$rowObject.addClass('drag-previous');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update block weights in the given region.
|
||||
*
|
||||
* @param {jQuery} table
|
||||
* Table with draggable items.
|
||||
* @param {string} region
|
||||
* Machine name of region containing blocks to update.
|
||||
*/
|
||||
function updateBlockWeights(table, region) {
|
||||
// Calculate minimum weight.
|
||||
let weight = -Math.round(table.find('.draggable').length / 2);
|
||||
// Update the block weights.
|
||||
table.find(`.region-${region}-message`).nextUntil('.region-title')
|
||||
.find('select.block-weight').val(() =>
|
||||
// Increment the weight before assigning it to prevent using the
|
||||
// absolute minimum available weight. This way we always have an
|
||||
// unused upper and lower bound, which makes manually setting the
|
||||
// weights easier for users who prefer to do it that way.
|
||||
++weight);
|
||||
}
|
||||
|
||||
const table = $('#blocks');
|
||||
// Get the blocks tableDrag object.
|
||||
const tableDrag = Drupal.tableDrag.blocks;
|
||||
// Add a handler for when a row is swapped, update empty regions.
|
||||
tableDrag.row.prototype.onSwap = function (swappedRow) {
|
||||
checkEmptyRegions(table, this);
|
||||
updateLastPlaced(table, this);
|
||||
};
|
||||
|
||||
// Add a handler so when a row is dropped, update fields dropped into
|
||||
// new regions.
|
||||
tableDrag.onDrop = function () {
|
||||
const dragObject = this;
|
||||
const $rowElement = $(dragObject.rowObject.element);
|
||||
// Use "region-message" row instead of "region" row because
|
||||
// "region-{region_name}-message" is less prone to regexp match errors.
|
||||
const regionRow = $rowElement.prevAll('tr.region-message').get(0);
|
||||
const regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
|
||||
const regionField = $rowElement.find('select.block-region-select');
|
||||
// Check whether the newly picked region is available for this block.
|
||||
if (regionField.find(`option[value=${regionName}]`).length === 0) {
|
||||
// If not, alert the user and keep the block in its old region
|
||||
// setting.
|
||||
window.alert(Drupal.t('The block cannot be placed in this region.'));
|
||||
// Simulate that there was a selected element change, so the row is
|
||||
// put back to from where the user tried to drag it.
|
||||
regionField.trigger('change');
|
||||
}
|
||||
|
||||
// Update region and weight fields if the region has been changed.
|
||||
if (!regionField.is(`.block-region-${regionName}`)) {
|
||||
const weightField = $rowElement.find('select.block-weight');
|
||||
const oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*block-weight-([^ ]+)([ ]+[^ ]+)*/, '$2');
|
||||
regionField.removeClass(`block-region-${oldRegionName}`).addClass(`block-region-${regionName}`);
|
||||
weightField.removeClass(`block-weight-${oldRegionName}`).addClass(`block-weight-${regionName}`);
|
||||
regionField.val(regionName);
|
||||
}
|
||||
|
||||
updateBlockWeights(table, regionName);
|
||||
};
|
||||
|
||||
// Add the behavior to each region select list.
|
||||
$(context).find('select.block-region-select').once('block-region-select')
|
||||
.on('change', function (event) {
|
||||
// Make our new row and select field.
|
||||
const row = $(this).closest('tr');
|
||||
const select = $(this);
|
||||
// Find the correct region and insert the row as the last in the
|
||||
// region.
|
||||
tableDrag.rowObject = new tableDrag.row(row[0]);
|
||||
const region_message = table.find(`.region-${select[0].value}-message`);
|
||||
const region_items = region_message.nextUntil('.region-message, .region-title');
|
||||
if (region_items.length) {
|
||||
region_items.last().after(row);
|
||||
}
|
||||
// We found that region_message is the last row.
|
||||
else {
|
||||
region_message.after(row);
|
||||
}
|
||||
updateBlockWeights(table, select[0].value);
|
||||
// Modify empty regions with added or removed fields.
|
||||
checkEmptyRegions(table, tableDrag.rowObject);
|
||||
// Update last placed block indication.
|
||||
updateLastPlaced(table, row);
|
||||
// Show unsaved changes warning.
|
||||
if (!tableDrag.changed) {
|
||||
$(Drupal.theme('tableDragChangedWarning')).insertBefore(tableDrag.table).hide().fadeIn('slow');
|
||||
tableDrag.changed = true;
|
||||
}
|
||||
// Remove focus from selectbox.
|
||||
select.trigger('blur');
|
||||
});
|
||||
},
|
||||
};
|
||||
}(jQuery, window, Drupal));
|
||||
+48
-132
@@ -1,38 +1,17 @@
|
||||
/**
|
||||
* @file
|
||||
* Block behaviors.
|
||||
*/
|
||||
* DO NOT EDIT THIS FILE.
|
||||
* See the following change record for more information,
|
||||
* https://www.drupal.org/node/2815083
|
||||
* @preserve
|
||||
**/
|
||||
|
||||
(function ($, window, Drupal) {
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Provide the summary information for the block settings vertical tabs.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the behavior for the block settings summaries.
|
||||
*/
|
||||
Drupal.behaviors.blockSettingsSummary = {
|
||||
attach: function () {
|
||||
// The drupalSetSummary method required for this behavior is not available
|
||||
// on the Blocks administration page, so we need to make sure this
|
||||
// behavior is processed only if drupalSetSummary is defined.
|
||||
attach: function attach() {
|
||||
if (typeof $.fn.drupalSetSummary === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a summary for checkboxes in the provided context.
|
||||
*
|
||||
* @param {HTMLDocument|HTMLElement} context
|
||||
* A context where one would find checkboxes to summarize.
|
||||
*
|
||||
* @return {string}
|
||||
* A string with the summary.
|
||||
*/
|
||||
function checkboxesSummary(context) {
|
||||
var vals = [];
|
||||
var $checkboxes = $(context).find('input[type="checkbox"]:checked + label');
|
||||
@@ -53,72 +32,37 @@
|
||||
if (!$pages.val()) {
|
||||
return Drupal.t('Not restricted');
|
||||
}
|
||||
else {
|
||||
return Drupal.t('Restricted to certain pages');
|
||||
}
|
||||
|
||||
return Drupal.t('Restricted to certain pages');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Move a block in the blocks table between regions via select list.
|
||||
*
|
||||
* This behavior is dependent on the tableDrag behavior, since it uses the
|
||||
* objects initialized in that behavior to update the row.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the tableDrag behaviour for blocks in block administration.
|
||||
*/
|
||||
Drupal.behaviors.blockDrag = {
|
||||
attach: function (context, settings) {
|
||||
// tableDrag is required and we should be on the blocks admin page.
|
||||
attach: function attach(context, settings) {
|
||||
if (typeof Drupal.tableDrag === 'undefined' || typeof Drupal.tableDrag.blocks === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to check empty regions and toggle classes based on this.
|
||||
*
|
||||
* @param {jQuery} table
|
||||
* The jQuery object representing the table to inspect.
|
||||
* @param {jQuery} rowObject
|
||||
* The jQuery object representing the table row.
|
||||
*/
|
||||
function checkEmptyRegions(table, rowObject) {
|
||||
table.find('tr.region-message').each(function () {
|
||||
var $this = $(this);
|
||||
// If the dragged row is in this region, but above the message row,
|
||||
// swap it down one space.
|
||||
|
||||
if ($this.prev('tr').get(0) === rowObject.element) {
|
||||
// Prevent a recursion problem when using the keyboard to move rows
|
||||
// up.
|
||||
if ((rowObject.method !== 'keyboard' || rowObject.direction === 'down')) {
|
||||
if (rowObject.method !== 'keyboard' || rowObject.direction === 'down') {
|
||||
rowObject.swap('after', this);
|
||||
}
|
||||
}
|
||||
// This region has become empty.
|
||||
|
||||
if ($this.next('tr').is(':not(.draggable)') || $this.next('tr').length === 0) {
|
||||
$this.removeClass('region-populated').addClass('region-empty');
|
||||
}
|
||||
// This region has become populated.
|
||||
else if ($this.is('.region-empty')) {
|
||||
$this.removeClass('region-empty').addClass('region-populated');
|
||||
}
|
||||
} else if ($this.is('.region-empty')) {
|
||||
$this.removeClass('region-empty').addClass('region-populated');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to update the last placed row with the correct classes.
|
||||
*
|
||||
* @param {jQuery} table
|
||||
* The jQuery object representing the table to inspect.
|
||||
* @param {jQuery} rowObject
|
||||
* The jQuery object representing the table row.
|
||||
*/
|
||||
function updateLastPlaced(table, rowObject) {
|
||||
// Remove the color-success class from new block if applicable.
|
||||
table.find('.color-success').removeClass('color-success');
|
||||
|
||||
var $rowObject = $(rowObject);
|
||||
@@ -128,58 +72,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update block weights in the given region.
|
||||
*
|
||||
* @param {jQuery} table
|
||||
* Table with draggable items.
|
||||
* @param {string} region
|
||||
* Machine name of region containing blocks to update.
|
||||
*/
|
||||
function updateBlockWeights(table, region) {
|
||||
// Calculate minimum weight.
|
||||
var weight = -Math.round(table.find('.draggable').length / 2);
|
||||
// Update the block weights.
|
||||
table.find('.region-' + region + '-message').nextUntil('.region-title')
|
||||
.find('select.block-weight').val(function () {
|
||||
// Increment the weight before assigning it to prevent using the
|
||||
// absolute minimum available weight. This way we always have an
|
||||
// unused upper and lower bound, which makes manually setting the
|
||||
// weights easier for users who prefer to do it that way.
|
||||
return ++weight;
|
||||
});
|
||||
|
||||
table.find('.region-' + region + '-message').nextUntil('.region-title').find('select.block-weight').val(function () {
|
||||
return ++weight;
|
||||
});
|
||||
}
|
||||
|
||||
var table = $('#blocks');
|
||||
// Get the blocks tableDrag object.
|
||||
|
||||
var tableDrag = Drupal.tableDrag.blocks;
|
||||
// Add a handler for when a row is swapped, update empty regions.
|
||||
|
||||
tableDrag.row.prototype.onSwap = function (swappedRow) {
|
||||
checkEmptyRegions(table, this);
|
||||
updateLastPlaced(table, this);
|
||||
};
|
||||
|
||||
// Add a handler so when a row is dropped, update fields dropped into
|
||||
// new regions.
|
||||
tableDrag.onDrop = function () {
|
||||
var dragObject = this;
|
||||
var $rowElement = $(dragObject.rowObject.element);
|
||||
// Use "region-message" row instead of "region" row because
|
||||
// "region-{region_name}-message" is less prone to regexp match errors.
|
||||
|
||||
var regionRow = $rowElement.prevAll('tr.region-message').get(0);
|
||||
var regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
|
||||
var regionField = $rowElement.find('select.block-region-select');
|
||||
// Check whether the newly picked region is available for this block.
|
||||
|
||||
if (regionField.find('option[value=' + regionName + ']').length === 0) {
|
||||
// If not, alert the user and keep the block in its old region
|
||||
// setting.
|
||||
window.alert(Drupal.t('The block cannot be placed in this region.'));
|
||||
// Simulate that there was a selected element change, so the row is
|
||||
// put back to from where the user tried to drag it.
|
||||
|
||||
regionField.trigger('change');
|
||||
}
|
||||
|
||||
// Update region and weight fields if the region has been changed.
|
||||
if (!regionField.is('.block-region-' + regionName)) {
|
||||
var weightField = $rowElement.find('select.block-weight');
|
||||
var oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*block-weight-([^ ]+)([ ]+[^ ]+)*/, '$2');
|
||||
@@ -191,38 +114,31 @@
|
||||
updateBlockWeights(table, regionName);
|
||||
};
|
||||
|
||||
// Add the behavior to each region select list.
|
||||
$(context).find('select.block-region-select').once('block-region-select')
|
||||
.on('change', function (event) {
|
||||
// Make our new row and select field.
|
||||
var row = $(this).closest('tr');
|
||||
var select = $(this);
|
||||
// Find the correct region and insert the row as the last in the
|
||||
// region.
|
||||
tableDrag.rowObject = new tableDrag.row(row[0]);
|
||||
var region_message = table.find('.region-' + select[0].value + '-message');
|
||||
var region_items = region_message.nextUntil('.region-message, .region-title');
|
||||
if (region_items.length) {
|
||||
region_items.last().after(row);
|
||||
}
|
||||
// We found that region_message is the last row.
|
||||
else {
|
||||
$(context).find('select.block-region-select').once('block-region-select').on('change', function (event) {
|
||||
var row = $(this).closest('tr');
|
||||
var select = $(this);
|
||||
|
||||
tableDrag.rowObject = new tableDrag.row(row[0]);
|
||||
var region_message = table.find('.region-' + select[0].value + '-message');
|
||||
var region_items = region_message.nextUntil('.region-message, .region-title');
|
||||
if (region_items.length) {
|
||||
region_items.last().after(row);
|
||||
} else {
|
||||
region_message.after(row);
|
||||
}
|
||||
updateBlockWeights(table, select[0].value);
|
||||
// Modify empty regions with added or removed fields.
|
||||
checkEmptyRegions(table, tableDrag.rowObject);
|
||||
// Update last placed block indication.
|
||||
updateLastPlaced(table, row);
|
||||
// Show unsaved changes warning.
|
||||
if (!tableDrag.changed) {
|
||||
$(Drupal.theme('tableDragChangedWarning')).insertBefore(tableDrag.table).hide().fadeIn('slow');
|
||||
tableDrag.changed = true;
|
||||
}
|
||||
// Remove focus from selectbox.
|
||||
select.trigger('blur');
|
||||
});
|
||||
updateBlockWeights(table, select[0].value);
|
||||
|
||||
checkEmptyRegions(table, tableDrag.rowObject);
|
||||
|
||||
updateLastPlaced(table, row);
|
||||
|
||||
if (!tableDrag.changed) {
|
||||
$(Drupal.theme('tableDragChangedWarning')).insertBefore(tableDrag.table).hide().fadeIn('slow');
|
||||
tableDrag.changed = true;
|
||||
}
|
||||
|
||||
select.trigger('blur');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
})(jQuery, window, Drupal);
|
||||
})(jQuery, window, Drupal);
|
||||
@@ -61,7 +61,7 @@ class BlockAccessControlHandler extends EntityAccessControlHandler implements En
|
||||
* @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
|
||||
* The lazy context repository service.
|
||||
*/
|
||||
public function __construct(EntityTypeInterface $entity_type, ContextHandlerInterface $context_handler, ContextRepositoryInterface $context_repository ) {
|
||||
public function __construct(EntityTypeInterface $entity_type, ContextHandlerInterface $context_handler, ContextRepositoryInterface $context_repository) {
|
||||
parent::__construct($entity_type);
|
||||
$this->contextHandler = $context_handler;
|
||||
$this->contextRepository = $context_repository;
|
||||
|
||||
@@ -15,6 +15,8 @@ interface BlockInterface extends ConfigEntityInterface {
|
||||
*
|
||||
* @deprecated in Drupal 8.3.x, will be removed before Drupal 9.0.0.
|
||||
* Use \Drupal\Core\Block\BlockPluginInterface::BLOCK_LABEL_VISIBLE.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2829775
|
||||
*/
|
||||
const BLOCK_LABEL_VISIBLE = BlockPluginInterface::BLOCK_LABEL_VISIBLE;
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
|
||||
*
|
||||
* @MigrateSource(
|
||||
* id = "block",
|
||||
* source_provider = "block"
|
||||
* source_module = "block"
|
||||
* )
|
||||
*/
|
||||
class Block extends DrupalSqlBase {
|
||||
@@ -84,7 +84,7 @@ class Block extends DrupalSqlBase {
|
||||
return [
|
||||
'bid' => $this->t('The block numeric identifier.'),
|
||||
'module' => $this->t('The module providing the block.'),
|
||||
'delta' => $this->t('The block\'s delta.'),
|
||||
'delta' => $this->t("The block's delta."),
|
||||
'theme' => $this->t('Which theme the block is placed in.'),
|
||||
'status' => $this->t('Whether or not the block is enabled.'),
|
||||
'weight' => $this->t('Weight of the block for ordering within regions.'),
|
||||
|
||||
@@ -2,11 +2,18 @@
|
||||
|
||||
namespace Drupal\block\Tests;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\BlockTestBase is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Instead, use \Drupal\Tests\block\Functional\BlockTestBase, see https://www.drupal.org/node/2901823.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
use Drupal\filter\Entity\FilterFormat;
|
||||
|
||||
/**
|
||||
* Provides setup and helper methods for block module tests.
|
||||
*
|
||||
* @deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0.
|
||||
* Use \Drupal\Tests\block\Functional\BlockTestBase.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2901823
|
||||
*/
|
||||
abstract class BlockTestBase extends WebTestBase {
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ package: Testing
|
||||
dependencies:
|
||||
- block
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
+3
-3
@@ -6,8 +6,8 @@ regions:
|
||||
content: Content
|
||||
help: Help
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
+3
-3
@@ -15,8 +15,8 @@ regions_hidden:
|
||||
- sidebar_first
|
||||
- sidebar_second
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -8,8 +8,8 @@ dependencies:
|
||||
- block
|
||||
- views
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\block\Entity\Block;
|
||||
use Drupal\Component\Render\FormattableMarkup;
|
||||
|
||||
/**
|
||||
* Provides test assertions for testing block appearance.
|
||||
*
|
||||
* Can be used by test classes that extend \Drupal\Tests\BrowserTestBase.
|
||||
*/
|
||||
trait AssertBlockAppearsTrait {
|
||||
|
||||
/**
|
||||
* Checks to see whether a block appears on the page.
|
||||
*
|
||||
* @param \Drupal\block\Entity\Block $block
|
||||
* The block entity to find on the page.
|
||||
*/
|
||||
protected function assertBlockAppears(Block $block) {
|
||||
$result = $this->findBlockInstance($block);
|
||||
$this->assertTrue(!empty($result), new FormattableMarkup('The block @id appears on the page', ['@id' => $block->id()]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see whether a block does not appears on the page.
|
||||
*
|
||||
* @param \Drupal\block\Entity\Block $block
|
||||
* The block entity to find on the page.
|
||||
*/
|
||||
protected function assertNoBlockAppears(Block $block) {
|
||||
$result = $this->findBlockInstance($block);
|
||||
$this->assertFalse(!empty($result), new FormattableMarkup('The block @id does not appear on the page', ['@id' => $block->id()]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a block instance on the page.
|
||||
*
|
||||
* @param \Drupal\block\Entity\Block $block
|
||||
* The block entity to find on the page.
|
||||
*
|
||||
* @return array
|
||||
* The result from the xpath query.
|
||||
*/
|
||||
protected function findBlockInstance(Block $block) {
|
||||
return $this->xpath('//div[@id = :id]', [':id' => 'block-' . $block->id()]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests the block system with admin themes.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockAdminThemeTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block', 'contextual'];
|
||||
|
||||
/**
|
||||
* Check for the accessibility of the admin theme on the block admin page.
|
||||
*/
|
||||
public function testAdminTheme() {
|
||||
// Create administrative user.
|
||||
$admin_user = $this->drupalCreateUser(['administer blocks', 'administer themes']);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
// Ensure that access to block admin page is denied when theme is not
|
||||
// installed.
|
||||
$this->drupalGet('admin/structure/block/list/bartik');
|
||||
$this->assertResponse(403);
|
||||
|
||||
// Install admin theme and confirm that tab is accessible.
|
||||
\Drupal::service('theme_handler')->install(['bartik']);
|
||||
$edit['admin_theme'] = 'bartik';
|
||||
$this->drupalPostForm('admin/appearance', $edit, t('Save configuration'));
|
||||
$this->drupalGet('admin/structure/block/list/bartik');
|
||||
$this->assertResponse(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure contextual links are disabled in Seven theme.
|
||||
*/
|
||||
public function testSevenAdminTheme() {
|
||||
// Create administrative user.
|
||||
$admin_user = $this->drupalCreateUser([
|
||||
'access administration pages',
|
||||
'administer themes',
|
||||
'access contextual links',
|
||||
'view the administration theme',
|
||||
]);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
// Install admin theme and confirm that tab is accessible.
|
||||
\Drupal::service('theme_handler')->install(['seven']);
|
||||
$edit['admin_theme'] = 'seven';
|
||||
$this->drupalPostForm('admin/appearance', $edit, t('Save configuration'));
|
||||
|
||||
// Define our block settings.
|
||||
$settings = [
|
||||
'theme' => 'seven',
|
||||
'region' => 'header',
|
||||
];
|
||||
|
||||
// Place a block.
|
||||
$block = $this->drupalPlaceBlock('local_tasks_block', $settings);
|
||||
|
||||
// Open admin page.
|
||||
$this->drupalGet('admin');
|
||||
|
||||
// Check if contextual link classes are unavailable.
|
||||
$this->assertNoRaw('<div data-contextual-id="block:block=' . $block->id() . ':langcode=en"></div>');
|
||||
$this->assertNoRaw('contextual-region');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests the block demo page with admin themes.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockDemoTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block'];
|
||||
|
||||
/**
|
||||
* Check for the accessibility of the admin block demo page.
|
||||
*/
|
||||
public function testBlockDemo() {
|
||||
// Create administrative user.
|
||||
$admin_user = $this->drupalCreateUser(['administer blocks', 'administer themes']);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
// Confirm we have access to the block demo page for the default theme.
|
||||
$config = $this->container->get('config.factory')->get('system.theme');
|
||||
$default_theme = $config->get('default');
|
||||
$this->drupalGet('admin/structure/block/demo/' . $default_theme);
|
||||
$this->assertResponse(200);
|
||||
$this->assertLinkByHref('admin/structure/block');
|
||||
$this->assertNoLinkByHref('admin/structure/block/list/' . $default_theme);
|
||||
|
||||
// All available themes in core.
|
||||
$available_themes = [
|
||||
'bartik',
|
||||
'classy',
|
||||
'seven',
|
||||
'stark',
|
||||
];
|
||||
|
||||
// All available themes minute minus the default theme.
|
||||
$themes = array_diff($available_themes, [$default_theme]);
|
||||
|
||||
foreach ($themes as $theme) {
|
||||
// Install theme.
|
||||
$this->container->get('theme_handler')->install([$theme]);
|
||||
// Confirm access to the block demo page for the theme.
|
||||
$this->drupalGet('admin/structure/block/demo/' . $theme);
|
||||
$this->assertResponse(200);
|
||||
// Confirm existence of link for "Exit block region demonstration".
|
||||
$this->assertLinkByHref('admin/structure/block/list/' . $theme);
|
||||
}
|
||||
|
||||
// Confirm access to the block demo page is denied for an invalid theme.
|
||||
$this->drupalGet('admin/structure/block/demo/invalid_theme');
|
||||
$this->assertResponse(403);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Component\Utility\Crypt;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests form in block caching.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockFormInBlockTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block', 'block_test', 'test_page_test'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Enable our test block.
|
||||
$this->drupalPlaceBlock('test_form_in_block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to see if form in block's redirect isn't cached.
|
||||
*/
|
||||
public function testCachePerPage() {
|
||||
$form_values = ['email' => 'test@example.com'];
|
||||
|
||||
// Go to "test-page" and test if the block is enabled.
|
||||
$this->drupalGet('test-page');
|
||||
$this->assertResponse(200);
|
||||
$this->assertText('Your .com email address.', 'form found');
|
||||
|
||||
// Make sure that we're currently still on /test-page after submitting the
|
||||
// form.
|
||||
$this->drupalPostForm(NULL, $form_values, t('Submit'));
|
||||
$this->assertUrl('test-page');
|
||||
$this->assertText(t('Your email address is @email', ['@email' => 'test@example.com']));
|
||||
|
||||
// Go to a different page and see if the block is enabled there as well.
|
||||
$this->drupalGet('test-render-title');
|
||||
$this->assertResponse(200);
|
||||
$this->assertText('Your .com email address.', 'form found');
|
||||
|
||||
// Make sure that submitting the form didn't redirect us to the first page
|
||||
// we submitted the form from after submitting the form from
|
||||
// /test-render-title.
|
||||
$this->drupalPostForm(NULL, $form_values, t('Submit'));
|
||||
$this->assertUrl('test-render-title');
|
||||
$this->assertText(t('Your email address is @email', ['@email' => 'test@example.com']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the actual placeholders
|
||||
*/
|
||||
public function testPlaceholders() {
|
||||
$this->drupalGet('test-multiple-forms');
|
||||
|
||||
$placeholder = 'form_action_' . Crypt::hashBase64('Drupal\Core\Form\FormBuilder::prepareForm');
|
||||
$this->assertText('Form action: ' . $placeholder, 'placeholder found.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests block module's installation.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockInstallTest extends BrowserTestBase {
|
||||
|
||||
public function testCacheTagInvalidationUponInstallation() {
|
||||
// Warm the page cache.
|
||||
$this->drupalGet('');
|
||||
$this->assertNoText('Powered by Drupal');
|
||||
$this->assertNoCacheTag('config:block_list');
|
||||
|
||||
// Install the block module, and place the "Powered by Drupal" block.
|
||||
$this->container->get('module_installer')->install(['block', 'shortcut']);
|
||||
$this->rebuildContainer();
|
||||
$this->container->get('router.builder')->rebuild();
|
||||
$this->drupalPlaceBlock('system_powered_by_block');
|
||||
|
||||
// Check the same page, block.module's hook_install() should have
|
||||
// invalidated the 'rendered' cache tag to make blocks show up.
|
||||
$this->drupalGet('');
|
||||
$this->assertCacheTag('config:block_list');
|
||||
$this->assertText('Powered by Drupal');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\language\Entity\ConfigurableLanguage;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests display of menu blocks with multiple languages.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockLanguageCacheTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block', 'language', 'menu_ui'];
|
||||
|
||||
/**
|
||||
* List of langcodes.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $langcodes = [];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Create test languages.
|
||||
$this->langcodes = [ConfigurableLanguage::load('en')];
|
||||
for ($i = 1; $i < 3; ++$i) {
|
||||
$language = ConfigurableLanguage::create([
|
||||
'id' => 'l' . $i,
|
||||
'label' => $this->randomString(),
|
||||
]);
|
||||
$language->save();
|
||||
$this->langcodes[$i] = $language;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a block in a language, check blocks page in all languages.
|
||||
*/
|
||||
public function testBlockLinks() {
|
||||
// Create admin user to be able to access block admin.
|
||||
$admin_user = $this->drupalCreateUser([
|
||||
'administer blocks',
|
||||
'access administration pages',
|
||||
'administer menu',
|
||||
]);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
// Create the block cache for all languages.
|
||||
foreach ($this->langcodes as $langcode) {
|
||||
$this->drupalGet('admin/structure/block', ['language' => $langcode]);
|
||||
$this->clickLink('Place block');
|
||||
}
|
||||
|
||||
// Create a menu in the default language.
|
||||
$edit['label'] = $this->randomMachineName();
|
||||
$edit['id'] = Unicode::strtolower($edit['label']);
|
||||
$this->drupalPostForm('admin/structure/menu/add', $edit, t('Save'));
|
||||
$this->assertText(t('Menu @label has been added.', ['@label' => $edit['label']]));
|
||||
|
||||
// Check that the block is listed for all languages.
|
||||
foreach ($this->langcodes as $langcode) {
|
||||
$this->drupalGet('admin/structure/block', ['language' => $langcode]);
|
||||
$this->clickLink('Place block');
|
||||
$this->assertText($edit['label']);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests blocks are being rendered in order by weight.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockRenderOrderTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['node', 'block'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Create a test user.
|
||||
$end_user = $this->drupalCreateUser([
|
||||
'access content',
|
||||
]);
|
||||
$this->drupalLogin($end_user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the render order of the blocks.
|
||||
*/
|
||||
public function testBlockRenderOrder() {
|
||||
// Enable test blocks and place them in the same region.
|
||||
$region = 'header';
|
||||
$test_blocks = [
|
||||
'stark_powered' => [
|
||||
'weight' => '-3',
|
||||
'id' => 'stark_powered',
|
||||
'label' => 'Test block A',
|
||||
],
|
||||
'stark_by' => [
|
||||
'weight' => '3',
|
||||
'id' => 'stark_by',
|
||||
'label' => 'Test block C',
|
||||
],
|
||||
'stark_drupal' => [
|
||||
'weight' => '3',
|
||||
'id' => 'stark_drupal',
|
||||
'label' => 'Test block B',
|
||||
],
|
||||
];
|
||||
|
||||
// Place the test blocks.
|
||||
foreach ($test_blocks as $test_block) {
|
||||
$this->drupalPlaceBlock('system_powered_by_block', [
|
||||
'label' => $test_block['label'],
|
||||
'region' => $region,
|
||||
'weight' => $test_block['weight'],
|
||||
'id' => $test_block['id'],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->drupalGet('');
|
||||
$test_content = $this->getRawContent('');
|
||||
|
||||
$controller = $this->container->get('entity_type.manager')->getStorage('block');
|
||||
foreach ($controller->loadMultiple() as $return_block) {
|
||||
$id = $return_block->id();
|
||||
if ($return_block_weight = $return_block->getWeight()) {
|
||||
$this->assertTrue($test_blocks[$id]['weight'] == $return_block_weight, 'Block weight is set as "' . $return_block_weight . '" for ' . $id . ' block.');
|
||||
$position[$id] = strpos($test_content, Html::getClass('block-' . $test_blocks[$id]['id']));
|
||||
}
|
||||
}
|
||||
$this->assertTrue($position['stark_powered'] < $position['stark_by'], 'Blocks with different weight are rendered in the correct order.');
|
||||
$this->assertTrue($position['stark_drupal'] < $position['stark_by'], 'Blocks with identical weight are rendered in alphabetical order.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
/**
|
||||
* Tests branding block display.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockSystemBrandingTest extends BlockTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block', 'system'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Set a site slogan.
|
||||
$this->config('system.site')
|
||||
->set('slogan', 'Community plumbing')
|
||||
->save();
|
||||
// Add the system branding block to the page.
|
||||
$this->drupalPlaceBlock('system_branding_block', ['region' => 'header', 'id' => 'site-branding']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests system branding block configuration.
|
||||
*/
|
||||
public function testSystemBrandingSettings() {
|
||||
$site_logo_xpath = '//div[@id="block-site-branding"]//a[@class="site-logo"]';
|
||||
$site_name_xpath = '//div[@id="block-site-branding"]//div[@class="site-name"]';
|
||||
$site_slogan_xpath = '//div[@id="block-site-branding"]//div[@class="site-slogan"]';
|
||||
|
||||
// Set default block settings.
|
||||
$this->drupalGet('');
|
||||
$site_logo_element = $this->xpath($site_logo_xpath);
|
||||
$site_name_element = $this->xpath($site_name_xpath);
|
||||
$site_slogan_element = $this->xpath($site_slogan_xpath);
|
||||
// Test that all branding elements are displayed.
|
||||
$this->assertTrue(!empty($site_logo_element), 'The branding block logo was found.');
|
||||
$this->assertTrue(!empty($site_name_element), 'The branding block site name was found.');
|
||||
$this->assertTrue(!empty($site_slogan_element), 'The branding block slogan was found.');
|
||||
$this->assertCacheTag('config:system.site');
|
||||
|
||||
// Be sure the slogan is XSS-filtered.
|
||||
$this->config('system.site')
|
||||
->set('slogan', '<script>alert("Community carpentry");</script>')
|
||||
->save();
|
||||
$this->drupalGet('');
|
||||
$site_slogan_element = $this->xpath($site_slogan_xpath);
|
||||
$this->assertEqual($site_slogan_element[0]->getText(), 'alert("Community carpentry");', 'The site slogan was XSS-filtered.');
|
||||
|
||||
// Turn just the logo off.
|
||||
$this->config('block.block.site-branding')
|
||||
->set('settings.use_site_logo', 0)
|
||||
->save();
|
||||
$this->drupalGet('');
|
||||
$site_logo_element = $this->xpath($site_logo_xpath);
|
||||
$site_name_element = $this->xpath($site_name_xpath);
|
||||
$site_slogan_element = $this->xpath($site_slogan_xpath);
|
||||
// Re-test all branding elements.
|
||||
$this->assertTrue(empty($site_logo_element), 'The branding block logo was disabled.');
|
||||
$this->assertTrue(!empty($site_name_element), 'The branding block site name was found.');
|
||||
$this->assertTrue(!empty($site_slogan_element), 'The branding block slogan was found.');
|
||||
$this->assertCacheTag('config:system.site');
|
||||
|
||||
// Turn just the site name off.
|
||||
$this->config('block.block.site-branding')
|
||||
->set('settings.use_site_logo', 1)
|
||||
->set('settings.use_site_name', 0)
|
||||
->save();
|
||||
$this->drupalGet('');
|
||||
$site_logo_element = $this->xpath($site_logo_xpath);
|
||||
$site_name_element = $this->xpath($site_name_xpath);
|
||||
$site_slogan_element = $this->xpath($site_slogan_xpath);
|
||||
// Re-test all branding elements.
|
||||
$this->assertTrue(!empty($site_logo_element), 'The branding block logo was found.');
|
||||
$this->assertTrue(empty($site_name_element), 'The branding block site name was disabled.');
|
||||
$this->assertTrue(!empty($site_slogan_element), 'The branding block slogan was found.');
|
||||
$this->assertCacheTag('config:system.site');
|
||||
|
||||
// Turn just the site slogan off.
|
||||
$this->config('block.block.site-branding')
|
||||
->set('settings.use_site_name', 1)
|
||||
->set('settings.use_site_slogan', 0)
|
||||
->save();
|
||||
$this->drupalGet('');
|
||||
$site_logo_element = $this->xpath($site_logo_xpath);
|
||||
$site_name_element = $this->xpath($site_name_xpath);
|
||||
$site_slogan_element = $this->xpath($site_slogan_xpath);
|
||||
// Re-test all branding elements.
|
||||
$this->assertTrue(!empty($site_logo_element), 'The branding block logo was found.');
|
||||
$this->assertTrue(!empty($site_name_element), 'The branding block site name was found.');
|
||||
$this->assertTrue(empty($site_slogan_element), 'The branding block slogan was disabled.');
|
||||
$this->assertCacheTag('config:system.site');
|
||||
|
||||
// Turn the site name and the site slogan off.
|
||||
$this->config('block.block.site-branding')
|
||||
->set('settings.use_site_name', 0)
|
||||
->set('settings.use_site_slogan', 0)
|
||||
->save();
|
||||
$this->drupalGet('');
|
||||
$site_logo_element = $this->xpath($site_logo_xpath);
|
||||
$site_name_element = $this->xpath($site_name_xpath);
|
||||
$site_slogan_element = $this->xpath($site_slogan_xpath);
|
||||
// Re-test all branding elements.
|
||||
$this->assertTrue(!empty($site_logo_element), 'The branding block logo was found.');
|
||||
$this->assertTrue(empty($site_name_element), 'The branding block site name was disabled.');
|
||||
$this->assertTrue(empty($site_slogan_element), 'The branding block slogan was disabled.');
|
||||
$this->assertCacheTag('config:system.site');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\block\Entity\Block;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\user\Entity\Role;
|
||||
use Drupal\user\RoleInterface;
|
||||
|
||||
/**
|
||||
* Tests basic block functionality.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockTest extends BlockTestBase {
|
||||
|
||||
/**
|
||||
* Tests block visibility.
|
||||
*/
|
||||
public function testBlockVisibility() {
|
||||
$block_name = 'system_powered_by_block';
|
||||
// Create a random title for the block.
|
||||
$title = $this->randomMachineName(8);
|
||||
// Enable a standard block.
|
||||
$default_theme = $this->config('system.theme')->get('default');
|
||||
$edit = [
|
||||
'id' => strtolower($this->randomMachineName(8)),
|
||||
'region' => 'sidebar_first',
|
||||
'settings[label]' => $title,
|
||||
'settings[label_display]' => TRUE,
|
||||
];
|
||||
// Set the block to be hidden on any user path, and to be shown only to
|
||||
// authenticated users.
|
||||
$edit['visibility[request_path][pages]'] = '/user*';
|
||||
$edit['visibility[request_path][negate]'] = TRUE;
|
||||
$edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
|
||||
$this->drupalGet('admin/structure/block/add/' . $block_name . '/' . $default_theme);
|
||||
$this->assertFieldChecked('edit-visibility-request-path-negate-0');
|
||||
|
||||
$this->drupalPostForm(NULL, $edit, t('Save block'));
|
||||
$this->assertText('The block configuration has been saved.', 'Block was saved');
|
||||
|
||||
$this->clickLink('Configure');
|
||||
$this->assertFieldChecked('edit-visibility-request-path-negate-1');
|
||||
|
||||
$this->drupalGet('');
|
||||
$this->assertText($title, 'Block was displayed on the front page.');
|
||||
|
||||
$this->drupalGet('user');
|
||||
$this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
|
||||
|
||||
// Confirm that the block is not displayed to anonymous users.
|
||||
$this->drupalLogout();
|
||||
$this->drupalGet('');
|
||||
$this->assertNoText($title, 'Block was not displayed to anonymous users.');
|
||||
|
||||
// Confirm that an empty block is not displayed.
|
||||
$this->assertNoText('Powered by Drupal', 'Empty block not displayed.');
|
||||
$this->assertNoRaw('sidebar-first', 'Empty sidebar-first region is not displayed.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that visibility can be properly toggled.
|
||||
*/
|
||||
public function testBlockToggleVisibility() {
|
||||
$block_name = 'system_powered_by_block';
|
||||
// Create a random title for the block.
|
||||
$title = $this->randomMachineName(8);
|
||||
// Enable a standard block.
|
||||
$default_theme = $this->config('system.theme')->get('default');
|
||||
$edit = [
|
||||
'id' => strtolower($this->randomMachineName(8)),
|
||||
'region' => 'sidebar_first',
|
||||
'settings[label]' => $title,
|
||||
];
|
||||
$block_id = $edit['id'];
|
||||
// Set the block to be shown only to authenticated users.
|
||||
$edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
|
||||
$this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
|
||||
$this->clickLink('Configure');
|
||||
$this->assertFieldChecked('edit-visibility-user-role-roles-authenticated');
|
||||
|
||||
$edit = [
|
||||
'visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']' => FALSE,
|
||||
];
|
||||
$this->drupalPostForm(NULL, $edit, 'Save block');
|
||||
$this->clickLink('Configure');
|
||||
$this->assertNoFieldChecked('edit-visibility-user-role-roles-authenticated');
|
||||
|
||||
// Ensure that no visibility is configured.
|
||||
/** @var \Drupal\block\BlockInterface $block */
|
||||
$block = Block::load($block_id);
|
||||
$visibility_config = $block->getVisibilityConditions()->getConfiguration();
|
||||
$this->assertIdentical([], $visibility_config);
|
||||
$this->assertIdentical([], $block->get('visibility'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test block visibility when leaving "pages" textarea empty.
|
||||
*/
|
||||
public function testBlockVisibilityListedEmpty() {
|
||||
$block_name = 'system_powered_by_block';
|
||||
// Create a random title for the block.
|
||||
$title = $this->randomMachineName(8);
|
||||
// Enable a standard block.
|
||||
$default_theme = $this->config('system.theme')->get('default');
|
||||
$edit = [
|
||||
'id' => strtolower($this->randomMachineName(8)),
|
||||
'region' => 'sidebar_first',
|
||||
'settings[label]' => $title,
|
||||
'visibility[request_path][negate]' => TRUE,
|
||||
];
|
||||
// Set the block to be hidden on any user path, and to be shown only to
|
||||
// authenticated users.
|
||||
$this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
|
||||
$this->assertText('The block configuration has been saved.', 'Block was saved');
|
||||
|
||||
$this->drupalGet('user');
|
||||
$this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
|
||||
|
||||
$this->drupalGet('USER');
|
||||
$this->assertNoText($title, 'Block was not displayed according to block visibility rules regardless of path case.');
|
||||
|
||||
// Confirm that the block is not displayed to anonymous users.
|
||||
$this->drupalLogout();
|
||||
$this->drupalGet('');
|
||||
$this->assertNoText($title, 'Block was not displayed to anonymous users on the front page.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests adding a block from the library page with a weight query string.
|
||||
*/
|
||||
public function testAddBlockFromLibraryWithWeight() {
|
||||
$default_theme = $this->config('system.theme')->get('default');
|
||||
// Test one positive, zero, and one negative weight.
|
||||
foreach (['7', '0', '-9'] as $weight) {
|
||||
$options = [
|
||||
'query' => [
|
||||
'region' => 'sidebar_first',
|
||||
'weight' => $weight,
|
||||
],
|
||||
];
|
||||
$this->drupalGet(Url::fromRoute('block.admin_library', ['theme' => $default_theme], $options));
|
||||
|
||||
$block_name = 'system_powered_by_block';
|
||||
$add_url = Url::fromRoute('block.admin_add', [
|
||||
'plugin_id' => $block_name,
|
||||
'theme' => $default_theme
|
||||
]);
|
||||
$links = $this->xpath('//a[contains(@href, :href)]', [':href' => $add_url->toString()]);
|
||||
$this->assertEqual(1, count($links), 'Found one matching link.');
|
||||
$this->assertEqual(t('Place block'), $links[0]->getText(), 'Found the expected link text.');
|
||||
|
||||
list($path, $query_string) = explode('?', $links[0]->getAttribute('href'), 2);
|
||||
parse_str($query_string, $query_parts);
|
||||
$this->assertEqual($weight, $query_parts['weight'], 'Found the expected weight query string.');
|
||||
|
||||
// Create a random title for the block.
|
||||
$title = $this->randomMachineName(8);
|
||||
$block_id = strtolower($this->randomMachineName(8));
|
||||
$edit = [
|
||||
'id' => $block_id,
|
||||
'settings[label]' => $title,
|
||||
];
|
||||
// Create the block using the link parsed from the library page.
|
||||
$this->drupalPostForm($this->getAbsoluteUrl($links[0]->getAttribute('href')), $edit, t('Save block'));
|
||||
|
||||
// Ensure that the block was created with the expected weight.
|
||||
/** @var \Drupal\block\BlockInterface $block */
|
||||
$block = Block::load($block_id);
|
||||
$this->assertEqual($weight, $block->getWeight(), 'Found the block with expected weight.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test configuring and moving a module-define block to specific regions.
|
||||
*/
|
||||
public function testBlock() {
|
||||
// Place page title block to test error messages.
|
||||
$this->drupalPlaceBlock('page_title_block');
|
||||
|
||||
// Disable the block.
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Disable');
|
||||
|
||||
// Select the 'Powered by Drupal' block to be configured and moved.
|
||||
$block = [];
|
||||
$block['id'] = 'system_powered_by_block';
|
||||
$block['settings[label]'] = $this->randomMachineName(8);
|
||||
$block['settings[label_display]'] = TRUE;
|
||||
$block['theme'] = $this->config('system.theme')->get('default');
|
||||
$block['region'] = 'header';
|
||||
|
||||
// Set block title to confirm that interface works and override any custom titles.
|
||||
$this->drupalPostForm('admin/structure/block/add/' . $block['id'] . '/' . $block['theme'], ['settings[label]' => $block['settings[label]'], 'settings[label_display]' => $block['settings[label_display]'], 'id' => $block['id'], 'region' => $block['region']], t('Save block'));
|
||||
$this->assertText(t('The block configuration has been saved.'), 'Block title set.');
|
||||
// Check to see if the block was created by checking its configuration.
|
||||
$instance = Block::load($block['id']);
|
||||
|
||||
$this->assertEqual($instance->label(), $block['settings[label]'], 'Stored block title found.');
|
||||
|
||||
// Check whether the block can be moved to all available regions.
|
||||
foreach ($this->regions as $region) {
|
||||
$this->moveBlockToRegion($block, $region);
|
||||
}
|
||||
|
||||
// Disable the block.
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Disable');
|
||||
|
||||
// Confirm that the block is now listed as disabled.
|
||||
$this->assertText(t('The block settings have been updated.'), 'Block successfully moved to disabled region.');
|
||||
|
||||
// Confirm that the block instance title and markup are not displayed.
|
||||
$this->drupalGet('node');
|
||||
$this->assertNoText(t($block['settings[label]']));
|
||||
// Check for <div id="block-my-block-instance-name"> if the machine name
|
||||
// is my_block_instance_name.
|
||||
$xpath = $this->buildXPathQuery('//div[@id=:id]/*', [':id' => 'block-' . str_replace('_', '-', strtolower($block['id']))]);
|
||||
$this->assertNoFieldByXPath($xpath, FALSE, 'Block found in no regions.');
|
||||
|
||||
// Test deleting the block from the edit form.
|
||||
$this->drupalGet('admin/structure/block/manage/' . $block['id']);
|
||||
$this->clickLink(t('Remove block'));
|
||||
$this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block['settings[label]']]));
|
||||
$this->drupalPostForm(NULL, [], t('Remove'));
|
||||
$this->assertRaw(t('The block %name has been removed.', ['%name' => $block['settings[label]']]));
|
||||
|
||||
// Test deleting a block via "Configure block" link.
|
||||
$block = $this->drupalPlaceBlock('system_powered_by_block');
|
||||
$this->drupalGet('admin/structure/block/manage/' . $block->id(), ['query' => ['destination' => 'admin']]);
|
||||
$this->clickLink(t('Remove block'));
|
||||
$this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block->label()]));
|
||||
$this->drupalPostForm(NULL, [], t('Remove'));
|
||||
$this->assertRaw(t('The block %name has been removed.', ['%name' => $block->label()]));
|
||||
$this->assertUrl('admin');
|
||||
$this->assertNoRaw($block->id());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the block form has a theme selector when not passed via the URL.
|
||||
*/
|
||||
public function testBlockThemeSelector() {
|
||||
// Install all themes.
|
||||
\Drupal::service('theme_handler')->install(['bartik', 'seven', 'stark']);
|
||||
$theme_settings = $this->config('system.theme');
|
||||
foreach (['bartik', 'seven', 'stark'] as $theme) {
|
||||
$this->drupalGet('admin/structure/block/list/' . $theme);
|
||||
$this->assertTitle(t('Block layout') . ' | Drupal');
|
||||
// Select the 'Powered by Drupal' block to be placed.
|
||||
$block = [];
|
||||
$block['id'] = strtolower($this->randomMachineName());
|
||||
$block['theme'] = $theme;
|
||||
$block['region'] = 'content';
|
||||
$this->drupalPostForm('admin/structure/block/add/system_powered_by_block', $block, t('Save block'));
|
||||
$this->assertText(t('The block configuration has been saved.'));
|
||||
$this->assertUrl('admin/structure/block/list/' . $theme . '?block-placement=' . Html::getClass($block['id']));
|
||||
|
||||
// Set the default theme and ensure the block is placed.
|
||||
$theme_settings->set('default', $theme)->save();
|
||||
$this->drupalGet('');
|
||||
$elements = $this->xpath('//div[@id = :id]', [':id' => Html::getUniqueId('block-' . $block['id'])]);
|
||||
$this->assertTrue(!empty($elements), 'The block was found.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test block display of theme titles.
|
||||
*/
|
||||
public function testThemeName() {
|
||||
// Enable the help block.
|
||||
$this->drupalPlaceBlock('help_block', ['region' => 'help']);
|
||||
$this->drupalPlaceBlock('local_tasks_block');
|
||||
// Explicitly set the default and admin themes.
|
||||
$theme = 'block_test_specialchars_theme';
|
||||
\Drupal::service('theme_handler')->install([$theme]);
|
||||
\Drupal::service('router.builder')->rebuild();
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->assertEscaped('<"Cat" & \'Mouse\'>');
|
||||
$this->drupalGet('admin/structure/block/list/block_test_specialchars_theme');
|
||||
$this->assertEscaped('Demonstrate block regions (<"Cat" & \'Mouse\'>)');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test block title display settings.
|
||||
*/
|
||||
public function testHideBlockTitle() {
|
||||
$block_name = 'system_powered_by_block';
|
||||
// Create a random title for the block.
|
||||
$title = $this->randomMachineName(8);
|
||||
$id = strtolower($this->randomMachineName(8));
|
||||
// Enable a standard block.
|
||||
$default_theme = $this->config('system.theme')->get('default');
|
||||
$edit = [
|
||||
'id' => $id,
|
||||
'region' => 'sidebar_first',
|
||||
'settings[label]' => $title,
|
||||
];
|
||||
$this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
|
||||
$this->assertText('The block configuration has been saved.', 'Block was saved');
|
||||
|
||||
$this->drupalGet('user');
|
||||
$this->assertNoText($title, 'Block title was not displayed by default.');
|
||||
|
||||
$edit = [
|
||||
'settings[label_display]' => TRUE,
|
||||
];
|
||||
$this->drupalPostForm('admin/structure/block/manage/' . $id, $edit, t('Save block'));
|
||||
$this->assertText('The block configuration has been saved.', 'Block was saved');
|
||||
|
||||
$this->drupalGet('admin/structure/block/manage/' . $id);
|
||||
$this->assertFieldChecked('edit-settings-label-display', 'The display_block option has the correct default value on the configuration form.');
|
||||
|
||||
$this->drupalGet('user');
|
||||
$this->assertText($title, 'Block title was displayed when enabled.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a block to a given region via the UI and confirms the result.
|
||||
*
|
||||
* @param array $block
|
||||
* An array of information about the block, including the following keys:
|
||||
* - module: The module providing the block.
|
||||
* - title: The title of the block.
|
||||
* - delta: The block's delta key.
|
||||
* @param string $region
|
||||
* The machine name of the theme region to move the block to, for example
|
||||
* 'header' or 'sidebar_first'.
|
||||
*/
|
||||
public function moveBlockToRegion(array $block, $region) {
|
||||
// Set the created block to a specific region.
|
||||
$block += ['theme' => $this->config('system.theme')->get('default')];
|
||||
$edit = [];
|
||||
$edit['blocks[' . $block['id'] . '][region]'] = $region;
|
||||
$this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
|
||||
|
||||
// Confirm that the block was moved to the proper region.
|
||||
$this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', ['%region_name' => $region]));
|
||||
|
||||
// Confirm that the block is being displayed.
|
||||
$this->drupalGet('');
|
||||
$this->assertText(t($block['settings[label]']), 'Block successfully being displayed on the page.');
|
||||
|
||||
// Confirm that the custom block was found at the proper region.
|
||||
$xpath = $this->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', [
|
||||
':region-class' => 'region region-' . Html::getClass($region),
|
||||
':block-id' => 'block-' . str_replace('_', '-', strtolower($block['id'])),
|
||||
]);
|
||||
$this->assertFieldByXPath($xpath, NULL, t('Block found in %region_name region.', ['%region_name' => Html::getClass($region)]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that cache tags are properly set and bubbled up to the page cache.
|
||||
*
|
||||
* Verify that invalidation of these cache tags works:
|
||||
* - "block:<block ID>"
|
||||
* - "block_plugin:<block plugin ID>"
|
||||
*/
|
||||
public function testBlockCacheTags() {
|
||||
// The page cache only works for anonymous users.
|
||||
$this->drupalLogout();
|
||||
|
||||
// Enable page caching.
|
||||
$config = $this->config('system.performance');
|
||||
$config->set('cache.page.max_age', 300);
|
||||
$config->save();
|
||||
|
||||
// Place the "Powered by Drupal" block.
|
||||
$block = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered']);
|
||||
|
||||
// Prime the page cache.
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
|
||||
|
||||
// Verify a cache hit, but also the presence of the correct cache tags in
|
||||
// both the page and block caches.
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
|
||||
$cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
|
||||
$cid = implode(':', $cid_parts);
|
||||
$cache_entry = \Drupal::cache('page')->get($cid);
|
||||
$expected_cache_tags = [
|
||||
'config:block_list',
|
||||
'block_view',
|
||||
'config:block.block.powered',
|
||||
'config:user.role.anonymous',
|
||||
'http_response',
|
||||
'rendered',
|
||||
];
|
||||
sort($expected_cache_tags);
|
||||
$keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
|
||||
$this->assertIdentical($cache_entry->tags, $expected_cache_tags);
|
||||
$cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
|
||||
$expected_cache_tags = [
|
||||
'block_view',
|
||||
'config:block.block.powered',
|
||||
'rendered',
|
||||
];
|
||||
sort($expected_cache_tags);
|
||||
$this->assertIdentical($cache_entry->tags, $expected_cache_tags);
|
||||
|
||||
// The "Powered by Drupal" block is modified; verify a cache miss.
|
||||
$block->setRegion('content');
|
||||
$block->save();
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
|
||||
|
||||
// Now we should have a cache hit again.
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
|
||||
|
||||
// Place the "Powered by Drupal" block another time; verify a cache miss.
|
||||
$block_2 = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered-2']);
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
|
||||
|
||||
// Verify a cache hit, but also the presence of the correct cache tags.
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
|
||||
$cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
|
||||
$cid = implode(':', $cid_parts);
|
||||
$cache_entry = \Drupal::cache('page')->get($cid);
|
||||
$expected_cache_tags = [
|
||||
'config:block_list',
|
||||
'block_view',
|
||||
'config:block.block.powered',
|
||||
'config:block.block.powered-2',
|
||||
'config:user.role.anonymous',
|
||||
'http_response',
|
||||
'rendered',
|
||||
];
|
||||
sort($expected_cache_tags);
|
||||
$this->assertEqual($cache_entry->tags, $expected_cache_tags);
|
||||
$expected_cache_tags = [
|
||||
'block_view',
|
||||
'config:block.block.powered',
|
||||
'rendered',
|
||||
];
|
||||
sort($expected_cache_tags);
|
||||
$keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
|
||||
$cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
|
||||
$this->assertIdentical($cache_entry->tags, $expected_cache_tags);
|
||||
$expected_cache_tags = [
|
||||
'block_view',
|
||||
'config:block.block.powered-2',
|
||||
'rendered',
|
||||
];
|
||||
sort($expected_cache_tags);
|
||||
$keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
|
||||
$cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:' . implode(':', $keys));
|
||||
$this->assertIdentical($cache_entry->tags, $expected_cache_tags);
|
||||
|
||||
// Now we should have a cache hit again.
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
|
||||
|
||||
// Delete the "Powered by Drupal" blocks; verify a cache miss.
|
||||
entity_delete_multiple('block', ['powered', 'powered-2']);
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that a link exists to block layout from the appearance form.
|
||||
*/
|
||||
public function testThemeAdminLink() {
|
||||
$this->drupalPlaceBlock('help_block', ['region' => 'help']);
|
||||
$theme_admin = $this->drupalCreateUser([
|
||||
'administer blocks',
|
||||
'administer themes',
|
||||
'access administration pages',
|
||||
]);
|
||||
$this->drupalLogin($theme_admin);
|
||||
$this->drupalGet('admin/appearance');
|
||||
$this->assertText('You can place blocks for each theme on the block layout page');
|
||||
$this->assertLinkByHref('admin/structure/block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that uninstalling a theme removes its block configuration.
|
||||
*/
|
||||
public function testUninstallTheme() {
|
||||
/** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
|
||||
$theme_handler = \Drupal::service('theme_handler');
|
||||
|
||||
$theme_handler->install(['seven']);
|
||||
$this->config('system.theme')->set('default', 'seven')->save();
|
||||
$block = $this->drupalPlaceBlock('system_powered_by_block', ['theme' => 'seven', 'region' => 'help']);
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertText('Powered by Drupal');
|
||||
|
||||
$this->config('system.theme')->set('default', 'classy')->save();
|
||||
$theme_handler->uninstall(['seven']);
|
||||
|
||||
// Ensure that the block configuration does not exist anymore.
|
||||
$this->assertIdentical(NULL, Block::load($block->id()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the block access.
|
||||
*/
|
||||
public function testBlockAccess() {
|
||||
$this->drupalPlaceBlock('test_access', ['region' => 'help']);
|
||||
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertNoText('Hello test world');
|
||||
|
||||
\Drupal::state()->set('test_block_access', TRUE);
|
||||
$this->drupalGet('<front>');
|
||||
$this->assertText('Hello test world');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests block_user_role_delete.
|
||||
*/
|
||||
public function testBlockUserRoleDelete() {
|
||||
$role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]);
|
||||
$role1->save();
|
||||
|
||||
$role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]);
|
||||
$role2->save();
|
||||
|
||||
$block = Block::create([
|
||||
'id' => $this->randomMachineName(),
|
||||
'plugin' => 'system_powered_by_block',
|
||||
]);
|
||||
|
||||
$block->setVisibilityConfig('user_role', [
|
||||
'roles' => [
|
||||
$role1->id() => $role1->id(),
|
||||
$role2->id() => $role2->id(),
|
||||
],
|
||||
]);
|
||||
|
||||
$block->save();
|
||||
|
||||
$this->assertEqual($block->getVisibility()['user_role']['roles'], [
|
||||
$role1->id() => $role1->id(),
|
||||
$role2->id() => $role2->id()
|
||||
]);
|
||||
|
||||
$role1->delete();
|
||||
|
||||
$block = Block::load($block->id());
|
||||
$this->assertEqual($block->getVisibility()['user_role']['roles'], [
|
||||
$role2->id() => $role2->id()
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\filter\Entity\FilterFormat;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Provides setup and helper methods for block module tests.
|
||||
*/
|
||||
abstract class BlockTestBase extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block', 'filter', 'test_page_test', 'help', 'block_test'];
|
||||
|
||||
/**
|
||||
* A list of theme regions to test.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $regions;
|
||||
|
||||
/**
|
||||
* A test user with administrative privileges.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $adminUser;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Use the test page as the front page.
|
||||
$this->config('system.site')->set('page.front', '/test-page')->save();
|
||||
|
||||
// Create Full HTML text format.
|
||||
$full_html_format = FilterFormat::create([
|
||||
'format' => 'full_html',
|
||||
'name' => 'Full HTML',
|
||||
]);
|
||||
$full_html_format->save();
|
||||
|
||||
// Create and log in an administrative user having access to the Full HTML
|
||||
// text format.
|
||||
$this->adminUser = $this->drupalCreateUser([
|
||||
'administer blocks',
|
||||
$full_html_format->getPermissionName(),
|
||||
'access administration pages',
|
||||
]);
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Define the existing regions.
|
||||
$this->regions = [
|
||||
'header',
|
||||
'sidebar_first',
|
||||
'content',
|
||||
'sidebar_second',
|
||||
'footer',
|
||||
];
|
||||
$block_storage = $this->container->get('entity_type.manager')->getStorage('block');
|
||||
$blocks = $block_storage->loadByProperties(['theme' => $this->config('system.theme')->get('default')]);
|
||||
foreach ($blocks as $block) {
|
||||
$block->delete();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests that the block configuration UI exists and stores data correctly.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockUiTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block', 'block_test', 'help', 'condition_test'];
|
||||
|
||||
protected $regions;
|
||||
|
||||
/**
|
||||
* The submitted block values used by this test.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $blockValues;
|
||||
|
||||
/**
|
||||
* The block entities used by this test.
|
||||
*
|
||||
* @var \Drupal\block\BlockInterface[]
|
||||
*/
|
||||
protected $blocks;
|
||||
|
||||
/**
|
||||
* An administrative user to configure the test environment.
|
||||
*/
|
||||
protected $adminUser;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Create and log in an administrative user.
|
||||
$this->adminUser = $this->drupalCreateUser([
|
||||
'administer blocks',
|
||||
'access administration pages',
|
||||
]);
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Enable some test blocks.
|
||||
$this->blockValues = [
|
||||
[
|
||||
'label' => 'Tools',
|
||||
'tr' => '5',
|
||||
'plugin_id' => 'system_menu_block:tools',
|
||||
'settings' => ['region' => 'sidebar_second', 'id' => 'tools'],
|
||||
'test_weight' => '-1',
|
||||
],
|
||||
[
|
||||
'label' => 'Powered by Drupal',
|
||||
'tr' => '16',
|
||||
'plugin_id' => 'system_powered_by_block',
|
||||
'settings' => ['region' => 'footer', 'id' => 'powered'],
|
||||
'test_weight' => '0',
|
||||
],
|
||||
];
|
||||
$this->blocks = [];
|
||||
foreach ($this->blockValues as $values) {
|
||||
$this->blocks[] = $this->drupalPlaceBlock($values['plugin_id'], $values['settings']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test block demo page exists and functions correctly.
|
||||
*/
|
||||
public function testBlockDemoUiPage() {
|
||||
$this->drupalPlaceBlock('help_block', ['region' => 'help']);
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink(t('Demonstrate block regions (@theme)', ['@theme' => 'Classy']));
|
||||
$elements = $this->xpath('//div[contains(@class, "region-highlighted")]/div[contains(@class, "block-region") and contains(text(), :title)]', [':title' => 'Highlighted']);
|
||||
$this->assertTrue(!empty($elements), 'Block demo regions are shown.');
|
||||
|
||||
\Drupal::service('theme_handler')->install(['test_theme']);
|
||||
$this->drupalGet('admin/structure/block/demo/test_theme');
|
||||
$this->assertEscaped('<strong>Test theme</strong>');
|
||||
|
||||
\Drupal::service('theme_handler')->install(['stable']);
|
||||
$this->drupalGet('admin/structure/block/demo/stable');
|
||||
$this->assertResponse(404, 'Hidden themes that are not the default theme are not supported by the block demo screen');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test block admin page exists and functions correctly.
|
||||
*/
|
||||
public function testBlockAdminUiPage() {
|
||||
// Visit the blocks admin ui.
|
||||
$this->drupalGet('admin/structure/block');
|
||||
// Look for the blocks table.
|
||||
$blocks_table = $this->xpath("//table[@id='blocks']");
|
||||
$this->assertTrue(!empty($blocks_table), 'The blocks table is being rendered.');
|
||||
// Look for test blocks in the table.
|
||||
foreach ($this->blockValues as $delta => $values) {
|
||||
$block = $this->blocks[$delta];
|
||||
$label = $block->label();
|
||||
$element = $this->xpath('//*[@id="blocks"]/tbody/tr[' . $values['tr'] . ']/td[1]/text()');
|
||||
$this->assertEquals($element[0]->getText(), $label, 'The "' . $label . '" block title is set inside the ' . $values['settings']['region'] . ' region.');
|
||||
// Look for a test block region select form element.
|
||||
$this->assertField('blocks[' . $values['settings']['id'] . '][region]', 'The block "' . $values['label'] . '" has a region assignment field.');
|
||||
// Move the test block to the header region.
|
||||
$edit['blocks[' . $values['settings']['id'] . '][region]'] = 'header';
|
||||
// Look for a test block weight select form element.
|
||||
$this->assertField('blocks[' . $values['settings']['id'] . '][weight]', 'The block "' . $values['label'] . '" has a weight assignment field.');
|
||||
// Change the test block's weight.
|
||||
$edit['blocks[' . $values['settings']['id'] . '][weight]'] = $values['test_weight'];
|
||||
}
|
||||
$this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
|
||||
foreach ($this->blockValues as $values) {
|
||||
// Check if the region and weight settings changes have persisted.
|
||||
$this->assertOptionSelected(
|
||||
'edit-blocks-' . $values['settings']['id'] . '-region',
|
||||
'header',
|
||||
'The block "' . $label . '" has the correct region assignment (header).'
|
||||
);
|
||||
$this->assertOptionSelected(
|
||||
'edit-blocks-' . $values['settings']['id'] . '-weight',
|
||||
$values['test_weight'],
|
||||
'The block "' . $label . '" has the correct weight assignment (' . $values['test_weight'] . ').'
|
||||
);
|
||||
}
|
||||
|
||||
// Add a block with a machine name the same as a region name.
|
||||
$this->drupalPlaceBlock('system_powered_by_block', ['region' => 'header', 'id' => 'header']);
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$element = $this->xpath('//tr[contains(@class, :class)]', [':class' => 'region-title-header']);
|
||||
$this->assertTrue(!empty($element));
|
||||
|
||||
// Ensure hidden themes do not appear in the UI. Enable another non base
|
||||
// theme and place the local tasks block.
|
||||
$this->assertTrue(\Drupal::service('theme_handler')->themeExists('classy'), 'The classy base theme is enabled');
|
||||
$this->drupalPlaceBlock('local_tasks_block', ['region' => 'header']);
|
||||
\Drupal::service('theme_installer')->install(['stable', 'stark']);
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$theme_handler = \Drupal::service('theme_handler');
|
||||
$this->assertLink($theme_handler->getName('classy'));
|
||||
$this->assertLink($theme_handler->getName('stark'));
|
||||
$this->assertNoLink($theme_handler->getName('stable'));
|
||||
|
||||
$this->drupalGet('admin/structure/block/list/stable');
|
||||
$this->assertResponse(404, 'Placing blocks through UI is not possible for a hidden base theme.');
|
||||
|
||||
\Drupal::configFactory()->getEditable('system.theme')->set('admin', 'stable')->save();
|
||||
\Drupal::service('router.builder')->rebuildIfNeeded();
|
||||
$this->drupalPlaceBlock('local_tasks_block', ['region' => 'header', 'theme' => 'stable']);
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->assertLink($theme_handler->getName('stable'));
|
||||
$this->drupalGet('admin/structure/block/list/stable');
|
||||
$this->assertResponse(200, 'Placing blocks through UI is possible for a hidden base theme that is the admin theme.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the block categories on the listing page.
|
||||
*/
|
||||
public function testCandidateBlockList() {
|
||||
$arguments = [
|
||||
':title' => 'Display message',
|
||||
':category' => 'Block test',
|
||||
':href' => 'admin/structure/block/add/test_block_instantiation/classy',
|
||||
];
|
||||
$pattern = '//tr[.//td/div[text()=:title] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]';
|
||||
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Place block');
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue(!empty($elements), 'The test block appears in the category for its module.');
|
||||
|
||||
// Trigger the custom category addition in block_test_block_alter().
|
||||
$this->container->get('state')->set('block_test_info_alter', TRUE);
|
||||
$this->container->get('plugin.manager.block')->clearCachedDefinitions();
|
||||
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Place block');
|
||||
$arguments[':category'] = 'Custom category';
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue(!empty($elements), 'The test block appears in a custom category controlled by block_test_block_alter().');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the behavior of unsatisfied context-aware blocks.
|
||||
*/
|
||||
public function testContextAwareUnsatisfiedBlocks() {
|
||||
$arguments = [
|
||||
':category' => 'Block test',
|
||||
':href' => 'admin/structure/block/add/test_context_aware_unsatisfied/classy',
|
||||
':text' => 'Test context-aware unsatisfied block',
|
||||
];
|
||||
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Place block');
|
||||
$elements = $this->xpath('//tr[.//td/div[text()=:text] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]', $arguments);
|
||||
$this->assertTrue(empty($elements), 'The context-aware test block does not appear.');
|
||||
|
||||
$definition = \Drupal::service('plugin.manager.block')->getDefinition('test_context_aware_unsatisfied');
|
||||
$this->assertTrue(!empty($definition), 'The context-aware test block does not exist.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the behavior of context-aware blocks.
|
||||
*/
|
||||
public function testContextAwareBlocks() {
|
||||
$expected_text = '<div id="test_context_aware--username">' . \Drupal::currentUser()->getUsername() . '</div>';
|
||||
$this->drupalGet('');
|
||||
$this->assertNoText('Test context-aware block');
|
||||
$this->assertNoRaw($expected_text);
|
||||
|
||||
$block_url = 'admin/structure/block/add/test_context_aware/classy';
|
||||
$arguments = [
|
||||
':title' => 'Test context-aware block',
|
||||
':category' => 'Block test',
|
||||
':href' => $block_url,
|
||||
];
|
||||
$pattern = '//tr[.//td/div[text()=:title] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]';
|
||||
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Place block');
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue(!empty($elements), 'The context-aware test block appears.');
|
||||
$definition = \Drupal::service('plugin.manager.block')->getDefinition('test_context_aware');
|
||||
$this->assertTrue(!empty($definition), 'The context-aware test block exists.');
|
||||
$edit = [
|
||||
'region' => 'content',
|
||||
'settings[context_mapping][user]' => '@block_test.multiple_static_context:userB',
|
||||
];
|
||||
$this->drupalPostForm($block_url, $edit, 'Save block');
|
||||
|
||||
$this->drupalGet('');
|
||||
$this->assertText('Test context-aware block');
|
||||
$this->assertText('User context found.');
|
||||
$this->assertRaw($expected_text);
|
||||
|
||||
// Test context mapping allows empty selection for optional contexts.
|
||||
$this->drupalGet('admin/structure/block/manage/testcontextawareblock');
|
||||
$edit = [
|
||||
'settings[context_mapping][user]' => '',
|
||||
];
|
||||
$this->drupalPostForm(NULL, $edit, 'Save block');
|
||||
$this->drupalGet('');
|
||||
$this->assertText('No context mapping selected.');
|
||||
$this->assertNoText('User context found.');
|
||||
|
||||
// Tests that conditions with missing context are not displayed.
|
||||
$this->drupalGet('admin/structure/block/manage/testcontextawareblock');
|
||||
$this->assertNoRaw('No existing type');
|
||||
$this->assertNoFieldByXPath('//*[@name="visibility[condition_test_no_existing_type][negate]"]');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the BlockForm populates machine name correctly.
|
||||
*/
|
||||
public function testMachineNameSuggestion() {
|
||||
$url = 'admin/structure/block/add/test_block_instantiation/classy';
|
||||
$this->drupalGet($url);
|
||||
$this->assertFieldByName('id', 'displaymessage', 'Block form uses raw machine name suggestion when no instance already exists.');
|
||||
$edit = ['region' => 'content'];
|
||||
$this->drupalPostForm($url, $edit, 'Save block');
|
||||
$this->assertText('The block configuration has been saved.');
|
||||
|
||||
// Now, check to make sure the form starts by autoincrementing correctly.
|
||||
$this->drupalGet($url);
|
||||
$this->assertFieldByName('id', 'displaymessage_2', 'Block form appends _2 to plugin-suggested machine name when an instance already exists.');
|
||||
$this->drupalPostForm($url, $edit, 'Save block');
|
||||
$this->assertText('The block configuration has been saved.');
|
||||
|
||||
// And verify that it continues working beyond just the first two.
|
||||
$this->drupalGet($url);
|
||||
$this->assertFieldByName('id', 'displaymessage_3', 'Block form appends _3 to plugin-suggested machine name when two instances already exist.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the block placement indicator.
|
||||
*/
|
||||
public function testBlockPlacementIndicator() {
|
||||
// Select the 'Powered by Drupal' block to be placed.
|
||||
$block = [];
|
||||
$block['id'] = strtolower($this->randomMachineName());
|
||||
$block['theme'] = 'classy';
|
||||
$block['region'] = 'content';
|
||||
|
||||
// After adding a block, it will indicate which block was just added.
|
||||
$this->drupalPostForm('admin/structure/block/add/system_powered_by_block', $block, t('Save block'));
|
||||
$this->assertUrl('admin/structure/block/list/classy?block-placement=' . Html::getClass($block['id']));
|
||||
|
||||
// Resaving the block page will remove the block indicator.
|
||||
$this->drupalPostForm(NULL, [], t('Save blocks'));
|
||||
$this->assertUrl('admin/structure/block/list/classy');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if validation errors are passed plugin form to the parent form.
|
||||
*/
|
||||
public function testBlockValidateErrors() {
|
||||
$this->drupalPostForm('admin/structure/block/add/test_settings_validation/classy', ['region' => 'content', 'settings[digits]' => 'abc'], t('Save block'));
|
||||
|
||||
$arguments = [':message' => 'Only digits are allowed'];
|
||||
$pattern = '//div[contains(@class,"messages messages--error")]/div[contains(text()[2],:message)]';
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue($elements, 'Plugin error message found in parent form.');
|
||||
|
||||
$error_class_pattern = '//div[contains(@class,"form-item-settings-digits")]/input[contains(@class,"error")]';
|
||||
$error_class = $this->xpath($error_class_pattern);
|
||||
$this->assertTrue($error_class, 'Plugin error class found in parent form.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the enable/disable routes are protected from CSRF.
|
||||
*/
|
||||
public function testRouteProtection() {
|
||||
// Get the first block generated in our setUp method.
|
||||
/** @var \Drupal\block\BlockInterface $block */
|
||||
$block = reset($this->blocks);
|
||||
// Ensure that the enable and disable routes are protected.
|
||||
$this->drupalGet('admin/structure/block/manage/' . $block->id() . '/disable');
|
||||
$this->assertResponse(403);
|
||||
$this->drupalGet('admin/structure/block/manage/' . $block->id() . '/enable');
|
||||
$this->assertResponse(403);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\block_content\Entity\BlockContent;
|
||||
use Drupal\block_content\Entity\BlockContentType;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\system\Entity\Menu;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
use Drupal\views\Entity\View;
|
||||
|
||||
/**
|
||||
* Tests that the block module properly escapes block descriptions.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockXssTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block', 'block_content', 'menu_ui', 'views'];
|
||||
|
||||
/**
|
||||
* Tests that nothing is escaped other than the blocks explicitly tested.
|
||||
*/
|
||||
public function testNoUnexpectedEscaping() {
|
||||
$this->drupalLogin($this->drupalCreateUser(['administer blocks', 'access administration pages']));
|
||||
$this->drupalGet(Url::fromRoute('block.admin_display'));
|
||||
$this->clickLink('Place block');
|
||||
$this->assertNoEscaped('<');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests XSS in title.
|
||||
*/
|
||||
public function testXssInTitle() {
|
||||
$this->container->get('module_installer')->install(['block_test']);
|
||||
$this->drupalPlaceBlock('test_xss_title', ['label' => '<script>alert("XSS label");</script>']);
|
||||
|
||||
\Drupal::state()->set('block_test.content', $this->randomMachineName());
|
||||
$this->drupalGet('');
|
||||
$this->assertNoRaw('<script>alert("XSS label");</script>', 'The block title was properly sanitized when rendered.');
|
||||
|
||||
$this->drupalLogin($this->drupalCreateUser(['administer blocks', 'access administration pages']));
|
||||
$default_theme = $this->config('system.theme')->get('default');
|
||||
$this->drupalGet('admin/structure/block/list/' . $default_theme);
|
||||
$this->assertNoRaw("<script>alert('XSS subject');</script>", 'The block title was properly sanitized in Block Plugin UI Admin page.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests XSS in category.
|
||||
*/
|
||||
public function testXssInCategory() {
|
||||
$this->container->get('module_installer')->install(['block_test']);
|
||||
$this->drupalPlaceBlock('test_xss_title');
|
||||
$this->drupalLogin($this->drupalCreateUser(['administer blocks', 'access administration pages']));
|
||||
$this->drupalGet(Url::fromRoute('block.admin_display'));
|
||||
$this->clickLink('Place block');
|
||||
$this->assertNoRaw("<script>alert('XSS category');</script>");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests various modules that provide blocks for XSS.
|
||||
*/
|
||||
public function testBlockXss() {
|
||||
$this->drupalLogin($this->rootUser);
|
||||
|
||||
$this->doViewTest();
|
||||
$this->doMenuTest();
|
||||
$this->doBlockContentTest();
|
||||
|
||||
$this->drupalGet(Url::fromRoute('block.admin_display'));
|
||||
$this->clickLink('Place block');
|
||||
$this->assertNoRaw('&lt;', 'The page does not have double escaped HTML tags.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests XSS coming from View block labels.
|
||||
*/
|
||||
protected function doViewTest() {
|
||||
// Create a View without a custom label for its block Display. The
|
||||
// admin_label of the block then becomes just the View's label.
|
||||
$view = View::create([
|
||||
'id' => $this->randomMachineName(),
|
||||
'label' => '<script>alert("view1");</script>',
|
||||
]);
|
||||
$view->addDisplay('block');
|
||||
$view->save();
|
||||
|
||||
// Create a View with a custom label for its block Display. The
|
||||
// admin_label of the block then becomes the View's label combined with
|
||||
// the Display's label.
|
||||
$view = View::create([
|
||||
'id' => $this->randomMachineName(),
|
||||
'label' => '<script>alert("view2");</script>',
|
||||
]);
|
||||
$view->addDisplay('block', 'Fish & chips');
|
||||
$view->save();
|
||||
|
||||
$this->drupalGet(Url::fromRoute('block.admin_display'));
|
||||
$this->clickLink('Place block');
|
||||
|
||||
// \Drupal\views\Plugin\Derivative\ViewsBlock::getDerivativeDefinitions()
|
||||
// has a different code path for an admin label based only on the View
|
||||
// label versus one based on both the View label and the Display label.
|
||||
// Ensure that this test is covering both code paths by asserting the
|
||||
// absence of a ":" for the first View and the presence of a ":" for the
|
||||
// second one. Note that the second assertion is redundant with the one
|
||||
// further down which also checks for the Display label, but is included
|
||||
// here for clarity.
|
||||
$this->assertNoEscaped('<script>alert("view1");</script>:');
|
||||
$this->assertEscaped('<script>alert("view2");</script>:');
|
||||
|
||||
// Assert that the blocks have their admin labels escaped and
|
||||
// don't appear anywhere unescaped.
|
||||
$this->assertEscaped('<script>alert("view1");</script>');
|
||||
$this->assertNoRaw('<script>alert("view1");</script>');
|
||||
$this->assertEscaped('<script>alert("view2");</script>: Fish & chips');
|
||||
$this->assertNoRaw('<script>alert("view2");</script>');
|
||||
$this->assertNoRaw('Fish & chips');
|
||||
|
||||
// Assert the Display label doesn't appear anywhere double escaped.
|
||||
$this->assertNoRaw('Fish & chips');
|
||||
$this->assertNoRaw('Fish &amp; chips');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests XSS coming from Menu block labels.
|
||||
*/
|
||||
protected function doMenuTest() {
|
||||
Menu::create([
|
||||
'id' => $this->randomMachineName(),
|
||||
'label' => '<script>alert("menu");</script>',
|
||||
])->save();
|
||||
|
||||
$this->drupalGet(Url::fromRoute('block.admin_display'));
|
||||
$this->clickLink('Place block');
|
||||
|
||||
$this->assertEscaped('<script>alert("menu");</script>');
|
||||
$this->assertNoRaw('<script>alert("menu");</script>');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests XSS coming from Block Content block info.
|
||||
*/
|
||||
protected function doBlockContentTest() {
|
||||
BlockContentType::create([
|
||||
'id' => 'basic',
|
||||
'label' => 'basic',
|
||||
'revision' => TRUE,
|
||||
])->save();
|
||||
BlockContent::create([
|
||||
'type' => 'basic',
|
||||
'info' => '<script>alert("block_content");</script>',
|
||||
])->save();
|
||||
|
||||
$this->drupalGet(Url::fromRoute('block.admin_display'));
|
||||
$this->clickLink('Place block');
|
||||
|
||||
$this->assertEscaped('<script>alert("block_content");</script>');
|
||||
$this->assertNoRaw('<script>alert("block_content");</script>');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional;
|
||||
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Tests the block administration page for a non-default theme.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class NonDefaultBlockAdminTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['block'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->drupalPlaceBlock('local_tasks_block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test non-default theme admin.
|
||||
*/
|
||||
public function testNonDefaultBlockAdmin() {
|
||||
$admin_user = $this->drupalCreateUser(['administer blocks', 'administer themes']);
|
||||
$this->drupalLogin($admin_user);
|
||||
$new_theme = 'bartik';
|
||||
\Drupal::service('theme_handler')->install([$new_theme]);
|
||||
$this->drupalGet('admin/structure/block/list/' . $new_theme);
|
||||
$this->assertText('Bartik(' . t('active tab') . ')', 'Tab for non-default theme found.');
|
||||
}
|
||||
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional\Update;
|
||||
|
||||
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
|
||||
|
||||
/**
|
||||
* Tests the upgrade path for block with conditions missing context.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2811519
|
||||
*
|
||||
* @group Update
|
||||
*/
|
||||
class BlockConditionMissingSchemaUpdateTest extends UpdatePathTestBase {
|
||||
|
||||
/**
|
||||
* This test does not have a failed update but the configuration has missing
|
||||
* schema so can not do the full post update testing offered by
|
||||
* UpdatePathTestBase.
|
||||
*
|
||||
* @var bool
|
||||
*
|
||||
* @see \Drupal\system\Tests\Update\UpdatePathTestBase::runUpdates()
|
||||
*/
|
||||
protected $checkFailedUpdates = FALSE;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['block_test', 'language'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setDatabaseDumpFiles() {
|
||||
$this->databaseDumpFiles = [
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
|
||||
__DIR__ . '/../../../fixtures/update/drupal-8.block-test-enabled-missing-schema.php',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that block context mapping is updated properly.
|
||||
*/
|
||||
public function testUpdateHookN() {
|
||||
$this->runUpdates();
|
||||
$this->drupalGet('<front>');
|
||||
// If the block is fixed by block_post_update_fix_negate_in_conditions()
|
||||
// then it will be visible.
|
||||
$this->assertText('Test missing schema on conditions');
|
||||
}
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional\Update;
|
||||
|
||||
/**
|
||||
* Runs BlockContextMappingUpdateTest with a dump filled with content.
|
||||
*
|
||||
* @group Update
|
||||
*/
|
||||
class BlockContextMappingUpdateFilledTest extends BlockContextMappingUpdateTest {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setDatabaseDumpFiles() {
|
||||
parent::setDatabaseDumpFiles();
|
||||
$this->databaseDumpFiles[0] = __DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.filled.standard.php.gz';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional\Update;
|
||||
|
||||
use Drupal\block\Entity\Block;
|
||||
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
|
||||
use Drupal\node\Entity\Node;
|
||||
|
||||
/**
|
||||
* Tests the upgrade path for block context mapping renames.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2354889
|
||||
*
|
||||
* @group Update
|
||||
*/
|
||||
class BlockContextMappingUpdateTest extends UpdatePathTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['block_test', 'language'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setDatabaseDumpFiles() {
|
||||
$this->databaseDumpFiles = [
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.block-context-manager-2354889.php',
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.language-enabled.php',
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.block-test-enabled.php',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that block context mapping is updated properly.
|
||||
*/
|
||||
public function testUpdateHookN() {
|
||||
$this->runUpdates();
|
||||
$this->assertRaw('Encountered an unknown context mapping key coming probably from a contributed or custom module: One or more mappings could not be updated. Please manually review your visibility settings for the following blocks, which are disabled now:<ul><li>User login (Visibility: Baloney spam)</li></ul>');
|
||||
|
||||
// Disable maintenance mode.
|
||||
\Drupal::state()->set('system.maintenance_mode', FALSE);
|
||||
|
||||
// We finished updating so we can log in the user now.
|
||||
$this->drupalLogin($this->rootUser);
|
||||
|
||||
// The block that we are testing has the following visibility rules:
|
||||
// - only visible on node pages
|
||||
// - only visible to authenticated users.
|
||||
$block_title = 'Test for 2354889';
|
||||
|
||||
// Create two nodes, a page and an article.
|
||||
$page = Node::create([
|
||||
'type' => 'page',
|
||||
'title' => 'Page node',
|
||||
]);
|
||||
$page->save();
|
||||
|
||||
$article = Node::create([
|
||||
'type' => 'article',
|
||||
'title' => 'Article node',
|
||||
]);
|
||||
$article->save();
|
||||
|
||||
// Check that the block appears only on Page nodes for authenticated users.
|
||||
$this->drupalGet('node/' . $page->id());
|
||||
$this->assertRaw($block_title, 'Test block is visible on a Page node as an authenticated user.');
|
||||
|
||||
$this->drupalGet('node/' . $article->id());
|
||||
$this->assertNoRaw($block_title, 'Test block is not visible on a Article node as an authenticated user.');
|
||||
|
||||
$this->drupalLogout();
|
||||
|
||||
// Check that the block does not appear on any page for anonymous users.
|
||||
$this->drupalGet('node/' . $page->id());
|
||||
$this->assertNoRaw($block_title, 'Test block is not visible on a Page node as an anonymous user.');
|
||||
|
||||
$this->drupalGet('node/' . $article->id());
|
||||
$this->assertNoRaw($block_title, 'Test block is not visible on a Article node as an anonymous user.');
|
||||
|
||||
// Ensure that all the context mappings got updated properly.
|
||||
$block = Block::load('testfor2354889');
|
||||
$visibility = $block->get('visibility');
|
||||
$this->assertEqual('@node.node_route_context:node', $visibility['node_type']['context_mapping']['node']);
|
||||
$this->assertEqual('@user.current_user_context:current_user', $visibility['user_role']['context_mapping']['user']);
|
||||
$this->assertEqual('@language.current_language_context:language_interface', $visibility['language']['context_mapping']['language']);
|
||||
|
||||
// Check that a block with invalid context is being disabled and that it can
|
||||
// still be edited afterward.
|
||||
$disabled_block = Block::load('thirdtestfor2354889');
|
||||
$this->assertFalse($disabled_block->status(), 'Block with invalid context is disabled');
|
||||
|
||||
$this->assertEqual(['thirdtestfor2354889' => ['missing_context_ids' => ['baloney_spam' => ['node_type']], 'status' => TRUE]], \Drupal::keyValue('update_backup')->get('block_update_8001'));
|
||||
|
||||
$disabled_block_visibility = $disabled_block->get('visibility');
|
||||
$this->assertTrue(!isset($disabled_block_visibility['node_type']), 'The problematic visibility condition has been removed.');
|
||||
|
||||
$admin_user = $this->drupalCreateUser(['administer blocks']);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
$this->drupalGet('admin/structure/block/manage/thirdtestfor2354889');
|
||||
$this->assertResponse('200');
|
||||
}
|
||||
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional\Update;
|
||||
|
||||
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
|
||||
|
||||
/**
|
||||
* Tests the upgrade path for removal of disabled region.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2513534
|
||||
*
|
||||
* @group Update
|
||||
*/
|
||||
class BlockRemoveDisabledRegionUpdateTest extends UpdatePathTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['block_test', 'language'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setDatabaseDumpFiles() {
|
||||
$this->databaseDumpFiles = [
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.update-test-block-disabled-2513534.php',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that block context mapping is updated properly.
|
||||
*/
|
||||
public function testUpdateHookN() {
|
||||
$this->runUpdates();
|
||||
|
||||
// Disable maintenance mode.
|
||||
\Drupal::state()->set('system.maintenance_mode', FALSE);
|
||||
|
||||
// We finished updating so we can login the user now.
|
||||
$this->drupalLogin($this->rootUser);
|
||||
|
||||
// Verify that a disabled block is in the default region.
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$element = $this->xpath("//tr[contains(@data-drupal-selector, :block) and contains(@class, :status)]//select/option[@selected and @value=:region]",
|
||||
[':block' => 'edit-blocks-pagetitle-1', ':status' => 'block-disabled', ':region' => 'header']);
|
||||
$this->assertTrue(!empty($element));
|
||||
|
||||
// Verify that an enabled block is now disabled and in the default region.
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$element = $this->xpath("//tr[contains(@data-drupal-selector, :block) and contains(@class, :status)]//select/option[@selected and @value=:region]",
|
||||
[':block' => 'edit-blocks-pagetitle-2', ':status' => 'block-disabled', ':region' => 'header']);
|
||||
$this->assertTrue(!empty($element));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Functional\Views;
|
||||
|
||||
use Drupal\Component\Serialization\Json;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Tests\block\Functional\AssertBlockAppearsTrait;
|
||||
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
|
||||
use Drupal\Tests\views\Functional\ViewTestBase;
|
||||
use Drupal\views\Entity\View;
|
||||
use Drupal\views\Views;
|
||||
use Drupal\views\Tests\ViewTestData;
|
||||
use Drupal\Core\Template\Attribute;
|
||||
|
||||
/**
|
||||
* Tests the block display plugin.
|
||||
*
|
||||
* @group block
|
||||
* @see \Drupal\views\Plugin\views\display\Block
|
||||
*/
|
||||
class DisplayBlockTest extends ViewTestBase {
|
||||
|
||||
use AssertPageCacheContextsAndTagsTrait;
|
||||
use AssertBlockAppearsTrait;
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['node', 'block_test_views', 'test_page_test', 'contextual', 'views_ui'];
|
||||
|
||||
/**
|
||||
* Views used by this test.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $testViews = ['test_view_block', 'test_view_block2'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp($import_test_views = TRUE) {
|
||||
parent::setUp($import_test_views);
|
||||
|
||||
ViewTestData::createTestViews(get_class($this), ['block_test_views']);
|
||||
$this->enableViewsTestModule();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests default and custom block categories.
|
||||
*/
|
||||
public function testBlockCategory() {
|
||||
$this->drupalLogin($this->drupalCreateUser(['administer views', 'administer blocks']));
|
||||
|
||||
// Create a new view in the UI.
|
||||
$edit = [];
|
||||
$edit['label'] = $this->randomString();
|
||||
$edit['id'] = strtolower($this->randomMachineName());
|
||||
$edit['show[wizard_key]'] = 'standard:views_test_data';
|
||||
$edit['description'] = $this->randomString();
|
||||
$edit['block[create]'] = TRUE;
|
||||
$edit['block[style][row_plugin]'] = 'fields';
|
||||
$this->drupalPostForm('admin/structure/views/add', $edit, t('Save and edit'));
|
||||
|
||||
$pattern = '//tr[.//td[text()=:category] and .//td//a[contains(@href, :href)]]';
|
||||
|
||||
// Test that the block was given a default category corresponding to its
|
||||
// base table.
|
||||
$arguments = [
|
||||
':href' => \Drupal::Url('block.admin_add', [
|
||||
'plugin_id' => 'views_block:' . $edit['id'] . '-block_1',
|
||||
'theme' => 'classy',
|
||||
]),
|
||||
':category' => 'Lists (Views)',
|
||||
];
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Place block');
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue(!empty($elements), 'The test block appears in the category for its base table.');
|
||||
|
||||
// Duplicate the block before changing the category.
|
||||
$this->drupalPostForm('admin/structure/views/view/' . $edit['id'] . '/edit/block_1', [], t('Duplicate @display_title', ['@display_title' => 'Block']));
|
||||
$this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_2');
|
||||
|
||||
// Change the block category to a random string.
|
||||
$this->drupalGet('admin/structure/views/view/' . $edit['id'] . '/edit/block_1');
|
||||
$link = $this->xpath('//a[@id="views-block-1-block-category" and normalize-space(text())=:category]', $arguments);
|
||||
$this->assertTrue(!empty($link));
|
||||
$this->clickLink(t('Lists (Views)'));
|
||||
$category = $this->randomString();
|
||||
$this->drupalPostForm(NULL, ['block_category' => $category], t('Apply'));
|
||||
|
||||
// Duplicate the block after changing the category.
|
||||
$this->drupalPostForm(NULL, [], t('Duplicate @display_title', ['@display_title' => 'Block']));
|
||||
$this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_3');
|
||||
|
||||
$this->drupalPostForm(NULL, [], t('Save'));
|
||||
|
||||
// Test that the blocks are listed under the correct categories.
|
||||
$arguments[':category'] = $category;
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$this->clickLink('Place block');
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue(!empty($elements), 'The test block appears in the custom category.');
|
||||
|
||||
$arguments = [
|
||||
':href' => \Drupal::Url('block.admin_add', [
|
||||
'plugin_id' => 'views_block:' . $edit['id'] . '-block_2',
|
||||
'theme' => 'classy',
|
||||
]),
|
||||
':category' => 'Lists (Views)',
|
||||
];
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue(!empty($elements), 'The first duplicated test block remains in the original category.');
|
||||
|
||||
$arguments = [
|
||||
':href' => \Drupal::Url('block.admin_add', [
|
||||
'plugin_id' => 'views_block:' . $edit['id'] . '-block_3',
|
||||
'theme' => 'classy',
|
||||
]),
|
||||
':category' => $category,
|
||||
];
|
||||
$elements = $this->xpath($pattern, $arguments);
|
||||
$this->assertTrue(!empty($elements), 'The second duplicated test block appears in the custom category.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests removing a block display.
|
||||
*/
|
||||
public function testDeleteBlockDisplay() {
|
||||
// To test all combinations possible we first place create two instances
|
||||
// of the block display of the first view.
|
||||
$block_1 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1']);
|
||||
$block_2 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:2']);
|
||||
|
||||
// Then we add one instance of blocks for each of the two displays of the
|
||||
// second view.
|
||||
$block_3 = $this->drupalPlaceBlock('views_block:test_view_block2-block_1', ['label' => 'test_view_block2-block_1']);
|
||||
$block_4 = $this->drupalPlaceBlock('views_block:test_view_block2-block_2', ['label' => 'test_view_block2-block_2']);
|
||||
|
||||
$this->drupalGet('test-page');
|
||||
$this->assertBlockAppears($block_1);
|
||||
$this->assertBlockAppears($block_2);
|
||||
$this->assertBlockAppears($block_3);
|
||||
$this->assertBlockAppears($block_4);
|
||||
|
||||
$block_storage = $this->container->get('entity_type.manager')->getStorage('block');
|
||||
|
||||
// Remove the block display, so both block entities from the first view
|
||||
// should both disappear.
|
||||
$view = Views::getView('test_view_block');
|
||||
$view->initDisplay();
|
||||
$view->displayHandlers->remove('block_1');
|
||||
$view->storage->save();
|
||||
|
||||
$this->assertFalse($block_storage->load($block_1->id()), 'The block for this display was removed.');
|
||||
$this->assertFalse($block_storage->load($block_2->id()), 'The block for this display was removed.');
|
||||
$this->assertTrue($block_storage->load($block_3->id()), 'A block from another view was unaffected.');
|
||||
$this->assertTrue($block_storage->load($block_4->id()), 'A block from another view was unaffected.');
|
||||
$this->drupalGet('test-page');
|
||||
$this->assertNoBlockAppears($block_1);
|
||||
$this->assertNoBlockAppears($block_2);
|
||||
$this->assertBlockAppears($block_3);
|
||||
$this->assertBlockAppears($block_4);
|
||||
|
||||
// Remove the first block display of the second view and ensure the block
|
||||
// instance of the second block display still exists.
|
||||
$view = Views::getView('test_view_block2');
|
||||
$view->initDisplay();
|
||||
$view->displayHandlers->remove('block_1');
|
||||
$view->storage->save();
|
||||
|
||||
$this->assertFalse($block_storage->load($block_3->id()), 'The block for this display was removed.');
|
||||
$this->assertTrue($block_storage->load($block_4->id()), 'A block from another display on the same view was unaffected.');
|
||||
$this->drupalGet('test-page');
|
||||
$this->assertNoBlockAppears($block_3);
|
||||
$this->assertBlockAppears($block_4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the block form for a Views block.
|
||||
*/
|
||||
public function testViewsBlockForm() {
|
||||
$this->drupalLogin($this->drupalCreateUser(['administer blocks']));
|
||||
$default_theme = $this->config('system.theme')->get('default');
|
||||
$this->drupalGet('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme);
|
||||
$elements = $this->xpath('//input[@name="label"]');
|
||||
$this->assertTrue(empty($elements), 'The label field is not found for Views blocks.');
|
||||
// Test that that machine name field is hidden from display and has been
|
||||
// saved as expected from the default value.
|
||||
$this->assertNoFieldById('edit-machine-name', 'views_block__test_view_block_1', 'The machine name is hidden on the views block form.');
|
||||
|
||||
// Save the block.
|
||||
$edit = ['region' => 'content'];
|
||||
$this->drupalPostForm(NULL, $edit, t('Save block'));
|
||||
$storage = $this->container->get('entity_type.manager')->getStorage('block');
|
||||
$block = $storage->load('views_block__test_view_block_block_1');
|
||||
// This will only return a result if our new block has been created with the
|
||||
// expected machine name.
|
||||
$this->assertTrue(!empty($block), 'The expected block was loaded.');
|
||||
|
||||
for ($i = 2; $i <= 3; $i++) {
|
||||
// Place the same block again and make sure we have a new ID.
|
||||
$this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
|
||||
$block = $storage->load('views_block__test_view_block_block_1_' . $i);
|
||||
// This will only return a result if our new block has been created with the
|
||||
// expected machine name.
|
||||
$this->assertTrue(!empty($block), 'The expected block was loaded.');
|
||||
}
|
||||
|
||||
// Tests the override capability of items per page.
|
||||
$this->drupalGet('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme);
|
||||
$edit = ['region' => 'content'];
|
||||
$edit['settings[override][items_per_page]'] = 10;
|
||||
|
||||
$this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
|
||||
|
||||
$block = $storage->load('views_block__test_view_block_block_1_4');
|
||||
$config = $block->getPlugin()->getConfiguration();
|
||||
$this->assertEqual(10, $config['items_per_page'], "'Items per page' is properly saved.");
|
||||
|
||||
$edit['settings[override][items_per_page]'] = 5;
|
||||
$this->drupalPostForm('admin/structure/block/manage/views_block__test_view_block_block_1_4', $edit, t('Save block'));
|
||||
|
||||
$block = $storage->load('views_block__test_view_block_block_1_4');
|
||||
|
||||
$config = $block->getPlugin()->getConfiguration();
|
||||
$this->assertEqual(5, $config['items_per_page'], "'Items per page' is properly saved.");
|
||||
|
||||
// Tests the override of the label capability.
|
||||
$edit = ['region' => 'content'];
|
||||
$edit['settings[views_label_checkbox]'] = 1;
|
||||
$edit['settings[views_label]'] = 'Custom title';
|
||||
$this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
|
||||
|
||||
$block = $storage->load('views_block__test_view_block_block_1_5');
|
||||
$config = $block->getPlugin()->getConfiguration();
|
||||
$this->assertEqual('Custom title', $config['views_label'], "'Label' is properly saved.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the actual rendering of the views block.
|
||||
*/
|
||||
public function testBlockRendering() {
|
||||
// Create a block and set a custom title.
|
||||
$block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']);
|
||||
$this->drupalGet('');
|
||||
|
||||
$result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
|
||||
$this->assertEqual($result[0]->getText(), 'Custom title');
|
||||
|
||||
// Don't override the title anymore.
|
||||
$plugin = $block->getPlugin();
|
||||
$plugin->setConfigurationValue('views_label', '');
|
||||
$block->save();
|
||||
|
||||
$this->drupalGet('');
|
||||
$result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
|
||||
$this->assertEqual($result[0]->getText(), 'test_view_block');
|
||||
|
||||
// Hide the title.
|
||||
$block->getPlugin()->setConfigurationValue('label_display', FALSE);
|
||||
$block->save();
|
||||
|
||||
$this->drupalGet('');
|
||||
$result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
|
||||
$this->assertTrue(empty($result), 'The title is not visible.');
|
||||
|
||||
$this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:system.site', 'config:views.view.test_view_block', 'http_response', 'rendered']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the various testcases of empty block rendering.
|
||||
*/
|
||||
public function testBlockEmptyRendering() {
|
||||
$url = new Url('test_page_test.test_page');
|
||||
// Remove all views_test_data entries.
|
||||
\Drupal::database()->truncate('views_test_data')->execute();
|
||||
/** @var \Drupal\views\ViewEntityInterface $view */
|
||||
$view = View::load('test_view_block');
|
||||
$view->invalidateCaches();
|
||||
|
||||
$block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']);
|
||||
$this->drupalGet('');
|
||||
$this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
|
||||
|
||||
$display = &$view->getDisplay('block_1');
|
||||
$display['display_options']['block_hide_empty'] = TRUE;
|
||||
$view->save();
|
||||
|
||||
$this->drupalGet($url);
|
||||
$this->assertEqual(0, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
|
||||
// Ensure that the view cacheability metadata is propagated even, for an
|
||||
// empty block.
|
||||
$this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
|
||||
$this->assertCacheContexts(['url.query_args:_wrapper_format']);
|
||||
|
||||
// Add a header displayed on empty result.
|
||||
$display = &$view->getDisplay('block_1');
|
||||
$display['display_options']['defaults']['header'] = FALSE;
|
||||
$display['display_options']['header']['example'] = [
|
||||
'field' => 'area_text_custom',
|
||||
'id' => 'area_text_custom',
|
||||
'table' => 'views',
|
||||
'plugin_id' => 'text_custom',
|
||||
'content' => 'test header',
|
||||
'empty' => TRUE,
|
||||
];
|
||||
$view->save();
|
||||
|
||||
$this->drupalGet($url);
|
||||
$this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
|
||||
$this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
|
||||
$this->assertCacheContexts(['url.query_args:_wrapper_format']);
|
||||
|
||||
// Hide the header on empty results.
|
||||
$display = &$view->getDisplay('block_1');
|
||||
$display['display_options']['defaults']['header'] = FALSE;
|
||||
$display['display_options']['header']['example'] = [
|
||||
'field' => 'area_text_custom',
|
||||
'id' => 'area_text_custom',
|
||||
'table' => 'views',
|
||||
'plugin_id' => 'text_custom',
|
||||
'content' => 'test header',
|
||||
'empty' => FALSE,
|
||||
];
|
||||
$view->save();
|
||||
|
||||
$this->drupalGet($url);
|
||||
$this->assertEqual(0, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
|
||||
$this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
|
||||
$this->assertCacheContexts(['url.query_args:_wrapper_format']);
|
||||
|
||||
// Add an empty text.
|
||||
$display = &$view->getDisplay('block_1');
|
||||
$display['display_options']['defaults']['empty'] = FALSE;
|
||||
$display['display_options']['empty']['example'] = [
|
||||
'field' => 'area_text_custom',
|
||||
'id' => 'area_text_custom',
|
||||
'table' => 'views',
|
||||
'plugin_id' => 'text_custom',
|
||||
'content' => 'test empty',
|
||||
];
|
||||
$view->save();
|
||||
|
||||
$this->drupalGet($url);
|
||||
$this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
|
||||
$this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
|
||||
$this->assertCacheContexts(['url.query_args:_wrapper_format']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the contextual links on a Views block.
|
||||
*/
|
||||
public function testBlockContextualLinks() {
|
||||
$this->drupalLogin($this->drupalCreateUser(['administer views', 'access contextual links', 'administer blocks']));
|
||||
$block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
|
||||
$cached_block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
|
||||
$this->drupalGet('test-page');
|
||||
|
||||
$id = 'block:block=' . $block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
|
||||
$cached_id = 'block:block=' . $cached_block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
|
||||
// @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder()
|
||||
$this->assertRaw('<div' . new Attribute(['data-contextual-id' => $id]) . '></div>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $id]));
|
||||
$this->assertRaw('<div' . new Attribute(['data-contextual-id' => $cached_id]) . '></div>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $cached_id]));
|
||||
|
||||
// Get server-rendered contextual links.
|
||||
// @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks()
|
||||
$post = ['ids[0]' => $id, 'ids[1]' => $cached_id];
|
||||
$url = 'contextual/render?_format=json,destination=test-page';
|
||||
$this->getSession()->getDriver()->getClient()->request('POST', $url, $post);
|
||||
$this->assertResponse(200);
|
||||
$json = Json::decode($this->getSession()->getPage()->getContent());
|
||||
$this->assertIdentical($json[$id], '<ul class="contextual-links"><li class="block-configure"><a href="' . base_path() . 'admin/structure/block/manage/' . $block->id() . '">Configure block</a></li><li class="entityviewedit-form"><a href="' . base_path() . 'admin/structure/views/view/test_view_block/edit/block_1">Edit view</a></li></ul>');
|
||||
$this->assertIdentical($json[$cached_id], '<ul class="contextual-links"><li class="block-configure"><a href="' . base_path() . 'admin/structure/block/manage/' . $cached_block->id() . '">Configure block</a></li><li class="entityviewedit-form"><a href="' . base_path() . 'admin/structure/views/view/test_view_block/edit/block_1">Edit view</a></li></ul>');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\FunctionalJavascript;
|
||||
|
||||
use Behat\Mink\Element\NodeElement;
|
||||
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
|
||||
|
||||
/**
|
||||
* Tests the JavaScript functionality of the block add filter.
|
||||
*
|
||||
* @group block
|
||||
*/
|
||||
class BlockFilterTest extends JavascriptTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['user', 'block'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$admin_user = $this->drupalCreateUser([
|
||||
'administer blocks',
|
||||
]);
|
||||
|
||||
$this->drupalLogin($admin_user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests block filter.
|
||||
*/
|
||||
public function testBlockFilter() {
|
||||
$this->drupalGet('admin/structure/block');
|
||||
$assertSession = $this->assertSession();
|
||||
$session = $this->getSession();
|
||||
$page = $session->getPage();
|
||||
|
||||
// Find the block filter field on the add-block dialog.
|
||||
$page->find('css', '#edit-blocks-region-header-title')->click();
|
||||
$filter = $assertSession->waitForElement('css', '.block-filter-text');
|
||||
|
||||
// Get all block rows, for assertions later.
|
||||
$block_rows = $page->findAll('css', '.block-add-table tbody tr');
|
||||
|
||||
// Test block filter reduces the number of visible rows.
|
||||
$filter->setValue('ad');
|
||||
$session->wait(10000, 'jQuery("#drupal-live-announce").html().indexOf("blocks are available") > -1');
|
||||
$visible_rows = $this->filterVisibleElements($block_rows);
|
||||
if (count($block_rows) > 0) {
|
||||
$this->assertNotEquals(count($block_rows), count($visible_rows));
|
||||
}
|
||||
|
||||
// Test Drupal.announce() message when multiple matches are expected.
|
||||
$expected_message = count($visible_rows) . ' blocks are available in the modified list.';
|
||||
$assertSession->elementTextContains('css', '#drupal-live-announce', $expected_message);
|
||||
|
||||
// Test Drupal.announce() message when only one match is expected.
|
||||
$filter->setValue('Powered by');
|
||||
$session->wait(10000, 'jQuery("#drupal-live-announce").html().indexOf("block is available") > -1');
|
||||
$visible_rows = $this->filterVisibleElements($block_rows);
|
||||
$this->assertEquals(1, count($visible_rows));
|
||||
$expected_message = '1 block is available in the modified list.';
|
||||
$assertSession->elementTextContains('css', '#drupal-live-announce', $expected_message);
|
||||
|
||||
// Test Drupal.announce() message when no matches are expected.
|
||||
$filter->setValue('Pan-Galactic Gargle Blaster');
|
||||
$session->wait(10000, 'jQuery("#drupal-live-announce").html().indexOf("0 blocks are available") > -1');
|
||||
$visible_rows = $this->filterVisibleElements($block_rows);
|
||||
$this->assertEquals(0, count($visible_rows));
|
||||
$expected_message = '0 blocks are available in the modified list.';
|
||||
$assertSession->elementTextContains('css', '#drupal-live-announce', $expected_message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes any non-visible elements from the passed array.
|
||||
*
|
||||
* @param NodeElement[] $elements
|
||||
* An array of node elements.
|
||||
*
|
||||
* @return NodeElement[]
|
||||
*/
|
||||
protected function filterVisibleElements(array $elements) {
|
||||
$elements = array_filter($elements, function (NodeElement $element) {
|
||||
return $element->isVisible();
|
||||
});
|
||||
return $elements;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block\Traits;
|
||||
|
||||
use Drupal\block\Entity\Block;
|
||||
|
||||
/**
|
||||
* Provides methods to create and place block with default settings.
|
||||
*
|
||||
* This trait is meant to be used only by test classes.
|
||||
*/
|
||||
trait BlockCreationTrait {
|
||||
|
||||
/**
|
||||
* Creates a block instance based on default settings.
|
||||
*
|
||||
* @param string $plugin_id
|
||||
* The plugin ID of the block type for this block instance.
|
||||
* @param array $settings
|
||||
* (optional) An associative array of settings for the block entity.
|
||||
* Override the defaults by specifying the key and value in the array, for
|
||||
* example:
|
||||
* @code
|
||||
* $this->drupalPlaceBlock('system_powered_by_block', array(
|
||||
* 'label' => t('Hello, world!'),
|
||||
* ));
|
||||
* @endcode
|
||||
* The following defaults are provided:
|
||||
* - label: Random string.
|
||||
* - ID: Random string.
|
||||
* - region: 'sidebar_first'.
|
||||
* - theme: The default theme.
|
||||
* - visibility: Empty array.
|
||||
*
|
||||
* @return \Drupal\block\Entity\Block
|
||||
* The block entity.
|
||||
*
|
||||
* @todo
|
||||
* Add support for creating custom block instances.
|
||||
*/
|
||||
protected function placeBlock($plugin_id, array $settings = []) {
|
||||
$config = \Drupal::configFactory();
|
||||
$settings += [
|
||||
'plugin' => $plugin_id,
|
||||
'region' => 'sidebar_first',
|
||||
'id' => strtolower($this->randomMachineName(8)),
|
||||
'theme' => $config->get('system.theme')->get('default'),
|
||||
'label' => $this->randomMachineName(8),
|
||||
'visibility' => [],
|
||||
'weight' => 0,
|
||||
];
|
||||
$values = [];
|
||||
foreach (['region', 'id', 'theme', 'plugin', 'weight', 'visibility'] as $key) {
|
||||
$values[$key] = $settings[$key];
|
||||
// Remove extra values that do not belong in the settings array.
|
||||
unset($settings[$key]);
|
||||
}
|
||||
foreach ($values['visibility'] as $id => $visibility) {
|
||||
$values['visibility'][$id]['id'] = $id;
|
||||
}
|
||||
$values['settings'] = $settings;
|
||||
$block = Block::create($values);
|
||||
$block->save();
|
||||
return $block;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,9 +16,9 @@ class BlockLocalTasksTest extends LocalTaskIntegrationTestBase {
|
||||
$this->directoryList = ['block' => 'core/modules/block'];
|
||||
parent::setUp();
|
||||
|
||||
$config_factory = $this->getConfigFactoryStub(['system.theme' => [
|
||||
'default' => 'test_c',
|
||||
]]);
|
||||
$config_factory = $this->getConfigFactoryStub([
|
||||
'system.theme' => ['default' => 'test_c'],
|
||||
]);
|
||||
|
||||
$themes = [];
|
||||
$themes['test_a'] = (object) [
|
||||
|
||||
@@ -10,8 +10,8 @@ dependencies:
|
||||
- user
|
||||
configure: entity.block_content.collection
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -18,7 +18,7 @@ function block_content_help($route_name, RouteMatchInterface $route_match) {
|
||||
$field_ui = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#';
|
||||
$output = '';
|
||||
$output .= '<h3>' . t('About') . '</h3>';
|
||||
$output .= '<p>' . t('The Custom Block module allows you to create and manage custom <em>block types</em> and <em>content-containing blocks</em> from the <a href = ":block-library" >Custom block library</a> page. Custom block types have fields; see the <a href=":field-help">Field module help</a> for more information. Once created, custom blocks can be placed in regions just like blocks provided by other modules; see the <a href=":blocks">Block module help</a> page for details. For more information, see the <a href=":online-help">online documentation for the Custom Block module</a>.', [':block-library' => \Drupal::url('entity.block_content.collection'), ':block-content' => \Drupal::url('entity.block_content.collection'), ':field-help' => \Drupal::url('help.page', ['name' => 'field']), ':blocks' => \Drupal::url('help.page', ['name' => 'block']), ':online-help' => 'https://www.drupal.org/documentation/modules/block_content']) . '</p>';
|
||||
$output .= '<p>' . t('The Custom Block module allows you to create and manage custom <em>block types</em> and <em>content-containing blocks</em> from the <a href=":block-library">Custom block library</a> page. Custom block types have fields; see the <a href=":field-help">Field module help</a> for more information. Once created, custom blocks can be placed in regions just like blocks provided by other modules; see the <a href=":blocks">Block module help</a> page for details. For more information, see the <a href=":online-help">online documentation for the Custom Block module</a>.', [':block-library' => \Drupal::url('entity.block_content.collection'), ':block-content' => \Drupal::url('entity.block_content.collection'), ':field-help' => \Drupal::url('help.page', ['name' => 'field']), ':blocks' => \Drupal::url('help.page', ['name' => 'block']), ':online-help' => 'https://www.drupal.org/documentation/modules/block_content']) . '</p>';
|
||||
$output .= '<h3>' . t('Uses') . '</h3>';
|
||||
$output .= '<dl>';
|
||||
$output .= '<dt>' . t('Creating and managing custom block types') . '</dt>';
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
services:
|
||||
block_content.uuid_lookup:
|
||||
class: \Drupal\block_content\BlockContentUuidLookup
|
||||
arguments: ['@cache.bootstrap', '@lock', '@entity_type.manager']
|
||||
tags:
|
||||
- { name: needs_destruction }
|
||||
@@ -19,6 +19,7 @@ source:
|
||||
type: string
|
||||
field_name:
|
||||
type: string
|
||||
source_module: block
|
||||
process:
|
||||
entity_type: entity_type
|
||||
bundle: bundle
|
||||
|
||||
@@ -22,6 +22,7 @@ source:
|
||||
type: string
|
||||
field_name:
|
||||
type: string
|
||||
source_module: block
|
||||
process:
|
||||
entity_type: entity_type
|
||||
bundle: bundle
|
||||
|
||||
@@ -20,6 +20,7 @@ source:
|
||||
type: string
|
||||
field_name:
|
||||
type: string
|
||||
source_module: block
|
||||
process:
|
||||
entity_type: entity_type
|
||||
bundle: bundle
|
||||
|
||||
@@ -12,6 +12,7 @@ source:
|
||||
ids:
|
||||
id:
|
||||
type: string
|
||||
source_module: block
|
||||
process:
|
||||
id: id
|
||||
label: label
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\block_content;
|
||||
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\Cache\CacheCollector;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Lock\LockBackendInterface;
|
||||
|
||||
/**
|
||||
* A cache collector that caches IDs for block_content UUIDs.
|
||||
*
|
||||
* As block_content entities are used as block plugin derivatives, it is a
|
||||
* fairly safe limitation that there are not hundreds of them, a site will
|
||||
* likely run into problems with too many block content entities in other places
|
||||
* than a cache that only stores UUID's and IDs. The same assumption is not true
|
||||
* for other content entities.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class BlockContentUuidLookup extends CacheCollector {
|
||||
|
||||
/**
|
||||
* The entity type manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
|
||||
*/
|
||||
protected $entityTypeManager;
|
||||
|
||||
/**
|
||||
* Constructs a BlockContentUuidLookup instance.
|
||||
*
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
|
||||
* The cache backend.
|
||||
* @param \Drupal\Core\Lock\LockBackendInterface $lock
|
||||
* The lock backend.
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
|
||||
* The entity type manager.
|
||||
*/
|
||||
public function __construct(CacheBackendInterface $cache, LockBackendInterface $lock, EntityTypeManagerInterface $entity_type_manager) {
|
||||
parent::__construct('block_content_uuid', $cache, $lock);
|
||||
$this->entityTypeManager = $entity_type_manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function resolveCacheMiss($key) {
|
||||
$ids = $this->entityTypeManager->getStorage('block_content')->getQuery()
|
||||
->condition('uuid', $key)
|
||||
->execute();
|
||||
|
||||
// Only cache if there is a match, otherwise creating new entities would
|
||||
// require to invalidate the cache.
|
||||
$id = reset($ids);
|
||||
if ($id) {
|
||||
$this->storage[$key] = $id;
|
||||
$this->persist($key);
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -42,6 +42,7 @@ use Drupal\user\UserInterface;
|
||||
* "delete-form" = "/block/{block_content}/delete",
|
||||
* "edit-form" = "/block/{block_content}",
|
||||
* "collection" = "/admin/structure/block/block-content",
|
||||
* "create" = "/block",
|
||||
* },
|
||||
* translatable = TRUE,
|
||||
* entity_keys = {
|
||||
@@ -52,6 +53,11 @@ use Drupal\user\UserInterface;
|
||||
* "langcode" = "langcode",
|
||||
* "uuid" = "uuid"
|
||||
* },
|
||||
* revision_metadata_keys = {
|
||||
* "revision_user" = "revision_user",
|
||||
* "revision_created" = "revision_created",
|
||||
* "revision_log_message" = "revision_log"
|
||||
* },
|
||||
* bundle_entity_type = "block_content_type",
|
||||
* field_ui_base_route = "entity.block_content_type.edit_form",
|
||||
* render_cache = FALSE,
|
||||
@@ -210,13 +216,6 @@ class BlockContent extends ContentEntityBase implements BlockContentInterface {
|
||||
->setSetting('target_type', 'user')
|
||||
->setRevisionable(TRUE);
|
||||
|
||||
$fields['revision_translation_affected'] = BaseFieldDefinition::create('boolean')
|
||||
->setLabel(t('Revision translation affected'))
|
||||
->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
|
||||
->setReadOnly(TRUE)
|
||||
->setRevisionable(TRUE)
|
||||
->setTranslatable(TRUE);
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace Drupal\block_content\Plugin\Block;
|
||||
|
||||
use Drupal\block_content\BlockContentUuidLookup;
|
||||
use Drupal\Core\Access\AccessResult;
|
||||
use Drupal\Core\Block\BlockBase;
|
||||
use Drupal\Core\Block\BlockManagerInterface;
|
||||
use Drupal\Core\Entity\EntityManagerInterface;
|
||||
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
|
||||
use Drupal\Core\Routing\UrlGeneratorInterface;
|
||||
@@ -32,11 +34,11 @@ class BlockContentBlock extends BlockBase implements ContainerFactoryPluginInter
|
||||
protected $blockManager;
|
||||
|
||||
/**
|
||||
* The entity manager service.
|
||||
* The entity type manager service.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityManagerInterface
|
||||
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
|
||||
*/
|
||||
protected $entityManager;
|
||||
protected $entityTypeManager;
|
||||
|
||||
/**
|
||||
* The Drupal account to use for checking for access to block.
|
||||
@@ -59,6 +61,20 @@ class BlockContentBlock extends BlockBase implements ContainerFactoryPluginInter
|
||||
*/
|
||||
protected $urlGenerator;
|
||||
|
||||
/**
|
||||
* The block content UUID lookup service.
|
||||
*
|
||||
* @var \Drupal\block_content\BlockContentUuidLookup
|
||||
*/
|
||||
protected $uuidLookup;
|
||||
|
||||
/**
|
||||
* The entity display repository.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
|
||||
*/
|
||||
protected $entityDisplayRepository;
|
||||
|
||||
/**
|
||||
* Constructs a new BlockContentBlock.
|
||||
*
|
||||
@@ -70,20 +86,26 @@ class BlockContentBlock extends BlockBase implements ContainerFactoryPluginInter
|
||||
* The plugin implementation definition.
|
||||
* @param \Drupal\Core\Block\BlockManagerInterface $block_manager
|
||||
* The Plugin Block Manager.
|
||||
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
|
||||
* The entity manager service.
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
|
||||
* The entity type manager service.
|
||||
* @param \Drupal\Core\Session\AccountInterface $account
|
||||
* The account for which view access should be checked.
|
||||
* @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
|
||||
* The URL generator.
|
||||
* @param \Drupal\block_content\BlockContentUuidLookup $uuid_lookup
|
||||
* The block content UUID lookup service.
|
||||
* @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
|
||||
* The entity display repository.
|
||||
*/
|
||||
public function __construct(array $configuration, $plugin_id, $plugin_definition, BlockManagerInterface $block_manager, EntityManagerInterface $entity_manager, AccountInterface $account, UrlGeneratorInterface $url_generator) {
|
||||
public function __construct(array $configuration, $plugin_id, $plugin_definition, BlockManagerInterface $block_manager, EntityTypeManagerInterface $entity_type_manager, AccountInterface $account, UrlGeneratorInterface $url_generator, BlockContentUuidLookup $uuid_lookup, EntityDisplayRepositoryInterface $entity_display_repository) {
|
||||
parent::__construct($configuration, $plugin_id, $plugin_definition);
|
||||
|
||||
$this->blockManager = $block_manager;
|
||||
$this->entityManager = $entity_manager;
|
||||
$this->entityTypeManager = $entity_type_manager;
|
||||
$this->account = $account;
|
||||
$this->urlGenerator = $url_generator;
|
||||
$this->uuidLookup = $uuid_lookup;
|
||||
$this->entityDisplayRepository = $entity_display_repository;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,9 +117,11 @@ class BlockContentBlock extends BlockBase implements ContainerFactoryPluginInter
|
||||
$plugin_id,
|
||||
$plugin_definition,
|
||||
$container->get('plugin.manager.block'),
|
||||
$container->get('entity.manager'),
|
||||
$container->get('entity_type.manager'),
|
||||
$container->get('current_user'),
|
||||
$container->get('url_generator')
|
||||
$container->get('url_generator'),
|
||||
$container->get('block_content.uuid_lookup'),
|
||||
$container->get('entity_display.repository')
|
||||
);
|
||||
}
|
||||
|
||||
@@ -118,9 +142,11 @@ class BlockContentBlock extends BlockBase implements ContainerFactoryPluginInter
|
||||
* Adds body and description fields to the block configuration form.
|
||||
*/
|
||||
public function blockForm($form, FormStateInterface $form_state) {
|
||||
$uuid = $this->getDerivativeId();
|
||||
$block = $this->entityManager->loadEntityByUuid('block_content', $uuid);
|
||||
$options = $this->entityManager->getViewModeOptionsByBundle('block_content', $block->bundle());
|
||||
$block = $this->getEntity();
|
||||
if (!$block) {
|
||||
return $form;
|
||||
}
|
||||
$options = $this->entityDisplayRepository->getViewModeOptionsByBundle('block_content', $block->bundle());
|
||||
|
||||
$form['view_mode'] = [
|
||||
'#type' => 'select',
|
||||
@@ -158,7 +184,7 @@ class BlockContentBlock extends BlockBase implements ContainerFactoryPluginInter
|
||||
*/
|
||||
public function build() {
|
||||
if ($block = $this->getEntity()) {
|
||||
return $this->entityManager->getViewBuilder($block->getEntityTypeId())->view($block, $this->configuration['view_mode']);
|
||||
return $this->entityTypeManager->getViewBuilder($block->getEntityTypeId())->view($block, $this->configuration['view_mode']);
|
||||
}
|
||||
else {
|
||||
return [
|
||||
@@ -180,7 +206,9 @@ class BlockContentBlock extends BlockBase implements ContainerFactoryPluginInter
|
||||
protected function getEntity() {
|
||||
if (!isset($this->blockContent)) {
|
||||
$uuid = $this->getDerivativeId();
|
||||
$this->blockContent = $this->entityManager->loadEntityByUuid('block_content', $uuid);
|
||||
if ($id = $this->uuidLookup->get($uuid)) {
|
||||
$this->blockContent = $this->entityTypeManager->getStorage('block_content')->load($id);
|
||||
}
|
||||
}
|
||||
return $this->blockContent;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
|
||||
* Drupal 6 block source from database.
|
||||
*
|
||||
* @MigrateSource(
|
||||
* id = "d6_box"
|
||||
* id = "d6_box",
|
||||
* source_module = "block"
|
||||
* )
|
||||
*/
|
||||
class Box extends DrupalSqlBase {
|
||||
|
||||
@@ -8,7 +8,8 @@ use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
|
||||
* Drupal 7 custom block source from database.
|
||||
*
|
||||
* @MigrateSource(
|
||||
* id = "d7_block_custom"
|
||||
* id = "d7_block_custom",
|
||||
* source_module = "block"
|
||||
* )
|
||||
*/
|
||||
class BlockCustom extends DrupalSqlBase {
|
||||
|
||||
+3
-3
@@ -7,8 +7,8 @@ package: Testing
|
||||
dependencies:
|
||||
- block_content
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
+3
-3
@@ -8,8 +8,8 @@ dependencies:
|
||||
- block_content
|
||||
- views
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -76,7 +76,7 @@ class BlockContentCacheTagsTest extends EntityCacheTagsTestBase {
|
||||
// Render the block.
|
||||
// @todo The request stack manipulation won't be necessary once
|
||||
// https://www.drupal.org/node/2367555 is fixed and the
|
||||
// corresponding $request->isMethodSafe() checks are removed from
|
||||
// corresponding $request->isMethodCacheable() checks are removed from
|
||||
// Drupal\Core\Render\Renderer.
|
||||
$request_stack = $this->container->get('request_stack');
|
||||
$request_stack->push(new Request());
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block_content\Functional;
|
||||
|
||||
use Drupal\block_content\Entity\BlockContentType;
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Tests\system\Functional\Menu\AssertBreadcrumbTrait;
|
||||
|
||||
/**
|
||||
* Ensures that custom block type functions work correctly.
|
||||
*
|
||||
* @group block_content
|
||||
*/
|
||||
class BlockContentTypeTest extends BlockContentTestBase {
|
||||
|
||||
use AssertBreadcrumbTrait;
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['field_ui'];
|
||||
|
||||
/**
|
||||
* Permissions to grant admin user.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $permissions = [
|
||||
'administer blocks',
|
||||
'administer block_content fields'
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether or not to create an initial block type.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $autoCreateBasicBlockType = FALSE;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->drupalPlaceBlock('page_title_block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests creating a block type programmatically and via a form.
|
||||
*/
|
||||
public function testBlockContentTypeCreation() {
|
||||
// Log in a test user.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Test the page with no block-types.
|
||||
$this->drupalGet('block/add');
|
||||
$this->assertResponse(200);
|
||||
$this->assertText('You have not created any block types yet');
|
||||
$this->clickLink('block type creation page');
|
||||
|
||||
// Create a block type via the user interface.
|
||||
$edit = [
|
||||
'id' => 'foo',
|
||||
'label' => 'title for foo',
|
||||
];
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$block_type = BlockContentType::load('foo');
|
||||
$this->assertTrue($block_type, 'The new block type has been created.');
|
||||
|
||||
$field_definitions = \Drupal::entityManager()->getFieldDefinitions('block_content', 'foo');
|
||||
$this->assertTrue(isset($field_definitions['body']), 'Body field created when using the UI to create block content types.');
|
||||
|
||||
// Check that the block type was created in site default language.
|
||||
$default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
|
||||
$this->assertEqual($block_type->language()->getId(), $default_langcode);
|
||||
|
||||
// Create block types programmatically.
|
||||
$this->createBlockContentType('basic', TRUE);
|
||||
$field_definitions = \Drupal::entityManager()->getFieldDefinitions('block_content', 'basic');
|
||||
$this->assertTrue(isset($field_definitions['body']), "Body field for 'basic' block type created when using the testing API to create block content types.");
|
||||
|
||||
$this->createBlockContentType('other');
|
||||
$field_definitions = \Drupal::entityManager()->getFieldDefinitions('block_content', 'other');
|
||||
$this->assertFalse(isset($field_definitions['body']), "Body field for 'other' block type not created when using the testing API to create block content types.");
|
||||
|
||||
$block_type = BlockContentType::load('other');
|
||||
$this->assertTrue($block_type, 'The new block type has been created.');
|
||||
|
||||
$this->drupalGet('block/add/' . $block_type->id());
|
||||
$this->assertResponse(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests editing a block type using the UI.
|
||||
*/
|
||||
public function testBlockContentTypeEditing() {
|
||||
$this->drupalPlaceBlock('system_breadcrumb_block');
|
||||
// Now create an initial block-type.
|
||||
$this->createBlockContentType('basic', TRUE);
|
||||
|
||||
$this->drupalLogin($this->adminUser);
|
||||
// We need two block types to prevent /block/add redirecting.
|
||||
$this->createBlockContentType('other');
|
||||
|
||||
$field_definitions = \Drupal::entityManager()->getFieldDefinitions('block_content', 'other');
|
||||
$this->assertFalse(isset($field_definitions['body']), 'Body field was not created when using the API to create block content types.');
|
||||
|
||||
// Verify that title and body fields are displayed.
|
||||
$this->drupalGet('block/add/basic');
|
||||
$this->assertRaw('Block description', 'Block info field was found.');
|
||||
$this->assertNotEmpty($this->cssSelect('#edit-body-0-value'), 'Body field was found.');
|
||||
|
||||
// Change the block type name.
|
||||
$edit = [
|
||||
'label' => 'Bar',
|
||||
];
|
||||
$this->drupalGet('admin/structure/block/block-content/manage/basic');
|
||||
$this->assertTitle(format_string('Edit @type custom block type | Drupal', ['@type' => 'basic']));
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$front_page_path = Url::fromRoute('<front>')->toString();
|
||||
$this->assertBreadcrumb('admin/structure/block/block-content/manage/basic/fields', [
|
||||
$front_page_path => 'Home',
|
||||
'admin/structure/block' => 'Block layout',
|
||||
'admin/structure/block/block-content' => 'Custom block library',
|
||||
'admin/structure/block/block-content/manage/basic' => 'Bar',
|
||||
]);
|
||||
\Drupal::entityManager()->clearCachedFieldDefinitions();
|
||||
|
||||
$this->drupalGet('block/add');
|
||||
$this->assertRaw('Bar', 'New name was displayed.');
|
||||
$this->clickLink('Bar');
|
||||
$this->assertUrl(\Drupal::url('block_content.add_form', ['block_content_type' => 'basic'], ['absolute' => TRUE]), [], 'Original machine name was used in URL.');
|
||||
|
||||
// Remove the body field.
|
||||
$this->drupalPostForm('admin/structure/block/block-content/manage/basic/fields/block_content.basic.body/delete', [], t('Delete'));
|
||||
// Resave the settings for this type.
|
||||
$this->drupalPostForm('admin/structure/block/block-content/manage/basic', [], t('Save'));
|
||||
// Check that the body field doesn't exist.
|
||||
$this->drupalGet('block/add/basic');
|
||||
$this->assertEmpty($this->cssSelect('#edit-body-0-value'), 'Body field was not found.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests deleting a block type that still has content.
|
||||
*/
|
||||
public function testBlockContentTypeDeletion() {
|
||||
// Now create an initial block-type.
|
||||
$this->createBlockContentType('basic', TRUE);
|
||||
|
||||
// Create a block type programmatically.
|
||||
$type = $this->createBlockContentType('foo');
|
||||
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Add a new block of this type.
|
||||
$block = $this->createBlockContent(FALSE, 'foo');
|
||||
// Attempt to delete the block type, which should not be allowed.
|
||||
$this->drupalGet('admin/structure/block/block-content/manage/' . $type->id() . '/delete');
|
||||
$this->assertRaw(
|
||||
t('%label is used by 1 custom block on your site. You can not remove this block type until you have removed all of the %label blocks.', ['%label' => $type->label()]),
|
||||
'The block type will not be deleted until all blocks of that type are removed.'
|
||||
);
|
||||
$this->assertNoText(t('This action cannot be undone.'), 'The block type deletion confirmation form is not available.');
|
||||
|
||||
// Delete the block.
|
||||
$block->delete();
|
||||
// Attempt to delete the block type, which should now be allowed.
|
||||
$this->drupalGet('admin/structure/block/block-content/manage/' . $type->id() . '/delete');
|
||||
$this->assertRaw(
|
||||
t('Are you sure you want to delete the custom block type %type?', ['%type' => $type->id()]),
|
||||
'The block type is available for deletion.'
|
||||
);
|
||||
$this->assertText(t('This action cannot be undone.'), 'The custom block type deletion confirmation form is available.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that redirects work as expected when multiple block types exist.
|
||||
*/
|
||||
public function testsBlockContentAddTypes() {
|
||||
// Now create an initial block-type.
|
||||
$this->createBlockContentType('basic', TRUE);
|
||||
|
||||
$this->drupalLogin($this->adminUser);
|
||||
// Create two block types programmatically.
|
||||
$type = $this->createBlockContentType('foo');
|
||||
$type = $this->createBlockContentType('bar');
|
||||
|
||||
// Get the custom block storage.
|
||||
$storage = $this->container
|
||||
->get('entity.manager')
|
||||
->getStorage('block_content');
|
||||
|
||||
// Install all themes.
|
||||
\Drupal::service('theme_handler')->install(['bartik', 'seven', 'stark']);
|
||||
$theme_settings = $this->config('system.theme');
|
||||
foreach (['bartik', 'seven', 'stark'] as $default_theme) {
|
||||
// Change the default theme.
|
||||
$theme_settings->set('default', $default_theme)->save();
|
||||
\Drupal::service('router.builder')->rebuild();
|
||||
|
||||
// For each installed theme, go to its block page and test the redirects.
|
||||
foreach (['bartik', 'seven', 'stark'] as $theme) {
|
||||
// Test that adding a block from the 'place blocks' form sends you to the
|
||||
// block configure form.
|
||||
$path = $theme == $default_theme ? 'admin/structure/block' : "admin/structure/block/list/$theme";
|
||||
$this->drupalGet($path);
|
||||
$this->clickLink('Place block');
|
||||
$this->clickLink(t('Add custom block'));
|
||||
// The seven theme has markup inside the link, we cannot use clickLink().
|
||||
if ($default_theme == 'seven') {
|
||||
$options = $theme != $default_theme ? ['query' => ['theme' => $theme]] : [];
|
||||
$this->assertLinkByHref(\Drupal::url('block_content.add_form', ['block_content_type' => 'foo'], $options));
|
||||
$this->drupalGet('block/add/foo', $options);
|
||||
}
|
||||
else {
|
||||
$this->clickLink('foo');
|
||||
}
|
||||
// Create a new block.
|
||||
$edit = ['info[0][value]' => $this->randomMachineName(8)];
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$blocks = $storage->loadByProperties(['info' => $edit['info[0][value]']]);
|
||||
if (!empty($blocks)) {
|
||||
$block = reset($blocks);
|
||||
$this->assertUrl(\Drupal::url('block.admin_add', ['plugin_id' => 'block_content:' . $block->uuid(), 'theme' => $theme], ['absolute' => TRUE]));
|
||||
$this->drupalPostForm(NULL, ['region' => 'content'], t('Save block'));
|
||||
$this->assertUrl(\Drupal::url('block.admin_display_theme', ['theme' => $theme], ['absolute' => TRUE, 'query' => ['block-placement' => Html::getClass($edit['info[0][value]'])]]));
|
||||
}
|
||||
else {
|
||||
$this->fail('Could not load created block.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test that adding a block from the 'custom blocks list' doesn't send you
|
||||
// to the block configure form.
|
||||
$this->drupalGet('admin/structure/block/block-content');
|
||||
$this->clickLink(t('Add custom block'));
|
||||
$this->clickLink('foo');
|
||||
$edit = ['info[0][value]' => $this->randomMachineName(8)];
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$blocks = $storage->loadByProperties(['info' => $edit['info[0][value]']]);
|
||||
if (!empty($blocks)) {
|
||||
$this->assertUrl(\Drupal::url('entity.block_content.collection', [], ['absolute' => TRUE]));
|
||||
}
|
||||
else {
|
||||
$this->fail('Could not load created block.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\block_content\Functional\Update;
|
||||
|
||||
use Drupal\Core\Field\BaseFieldDefinition;
|
||||
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
|
||||
|
||||
/**
|
||||
* Tests update functions for the Block Content module.
|
||||
*
|
||||
* @group Update
|
||||
*/
|
||||
class BlockContentUpdateTest extends UpdatePathTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setDatabaseDumpFiles() {
|
||||
$this->databaseDumpFiles = [
|
||||
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the revision metadata fields and revision data table additions.
|
||||
*/
|
||||
public function testSimpleUpdates() {
|
||||
$entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
|
||||
$entity_type = $entity_definition_update_manager->getEntityType('block_content');
|
||||
$this->assertNull($entity_type->getRevisionDataTable());
|
||||
|
||||
$this->runUpdates();
|
||||
|
||||
$post_revision_created = $entity_definition_update_manager->getFieldStorageDefinition('revision_created', 'block_content');
|
||||
$post_revision_user = $entity_definition_update_manager->getFieldStorageDefinition('revision_user', 'block_content');
|
||||
$this->assertTrue($post_revision_created instanceof BaseFieldDefinition, "Revision created field found");
|
||||
$this->assertTrue($post_revision_user instanceof BaseFieldDefinition, "Revision user field found");
|
||||
|
||||
$this->assertEqual('created', $post_revision_created->getType(), "Field is type created");
|
||||
$this->assertEqual('entity_reference', $post_revision_user->getType(), "Field is type entity_reference");
|
||||
|
||||
$entity_type = $entity_definition_update_manager->getEntityType('block_content');
|
||||
$this->assertEqual('block_content_field_revision', $entity_type->getRevisionDataTable());
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -35,7 +35,7 @@ class MigrateBlockContentEntityFormDisplayTest extends MigrateDrupal7TestBase {
|
||||
*
|
||||
* @param string $id
|
||||
* The entity ID.
|
||||
* @param string $component
|
||||
* @param string $component_id
|
||||
* The ID of the form component.
|
||||
*/
|
||||
protected function assertDisplay($id, $component_id) {
|
||||
|
||||
@@ -19,9 +19,9 @@ class BlockContentLocalTasksTest extends LocalTaskIntegrationTestBase {
|
||||
];
|
||||
parent::setUp();
|
||||
|
||||
$config_factory = $this->getConfigFactoryStub(['system.theme' => [
|
||||
'default' => 'test_c',
|
||||
]]);
|
||||
$config_factory = $this->getConfigFactoryStub([
|
||||
'system.theme' => ['default' => 'test_c'],
|
||||
]);
|
||||
|
||||
$themes = [];
|
||||
$themes['test_a'] = (object) [
|
||||
|
||||
@@ -4,11 +4,12 @@ description: 'Allow administrators to place blocks from any Drupal page'
|
||||
package: Core (Experimental)
|
||||
# version: VERSION
|
||||
# core: 8.x
|
||||
hidden: true
|
||||
dependencies:
|
||||
- block
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* @file
|
||||
* Javascript behaviors for the Book module.
|
||||
*/
|
||||
|
||||
(function ($, Drupal) {
|
||||
/**
|
||||
* Adds summaries to the book outline form.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches summary behavior to book outline forms.
|
||||
*/
|
||||
Drupal.behaviors.bookDetailsSummaries = {
|
||||
attach(context) {
|
||||
$(context).find('.book-outline-form').drupalSetSummary((context) => {
|
||||
const $select = $(context).find('.book-title-select');
|
||||
const val = $select.val();
|
||||
|
||||
if (val === '0') {
|
||||
return Drupal.t('Not in book');
|
||||
}
|
||||
else if (val === 'new') {
|
||||
return Drupal.t('New book');
|
||||
}
|
||||
|
||||
return Drupal.checkPlain($select.find(':selected').text());
|
||||
});
|
||||
},
|
||||
};
|
||||
}(jQuery, Drupal));
|
||||
@@ -8,8 +8,8 @@ dependencies:
|
||||
- node
|
||||
configure: book.settings
|
||||
|
||||
# Information added by Drupal.org packaging script on 2017-08-16
|
||||
version: '8.3.7'
|
||||
# Information added by Drupal.org packaging script on 2017-11-03
|
||||
version: '8.4.2'
|
||||
core: '8.x'
|
||||
project: 'drupal'
|
||||
datestamp: 1502903957
|
||||
datestamp: 1509719929
|
||||
|
||||
+10
-22
@@ -1,37 +1,25 @@
|
||||
/**
|
||||
* @file
|
||||
* Javascript behaviors for the Book module.
|
||||
*/
|
||||
* DO NOT EDIT THIS FILE.
|
||||
* See the following change record for more information,
|
||||
* https://www.drupal.org/node/2815083
|
||||
* @preserve
|
||||
**/
|
||||
|
||||
(function ($, Drupal) {
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Adds summaries to the book outline form.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches summary behavior to book outline forms.
|
||||
*/
|
||||
Drupal.behaviors.bookDetailsSummaries = {
|
||||
attach: function (context) {
|
||||
attach: function attach(context) {
|
||||
$(context).find('.book-outline-form').drupalSetSummary(function (context) {
|
||||
var $select = $(context).find('.book-title-select');
|
||||
var val = $select.val();
|
||||
|
||||
if (val === '0') {
|
||||
return Drupal.t('Not in book');
|
||||
}
|
||||
else if (val === 'new') {
|
||||
} else if (val === 'new') {
|
||||
return Drupal.t('New book');
|
||||
}
|
||||
else {
|
||||
return Drupal.checkPlain($select.find(':selected').text());
|
||||
}
|
||||
|
||||
return Drupal.checkPlain($select.find(':selected').text());
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
})(jQuery, Drupal);
|
||||
})(jQuery, Drupal);
|
||||
@@ -82,7 +82,8 @@ function book_entity_type_build(array &$entity_types) {
|
||||
$entity_types['node']
|
||||
->setFormClass('book_outline', 'Drupal\book\Form\BookOutlineForm')
|
||||
->setLinkTemplate('book-outline-form', '/node/{node}/outline')
|
||||
->setLinkTemplate('book-remove-form', '/node/{node}/outline/remove');
|
||||
->setLinkTemplate('book-remove-form', '/node/{node}/outline/remove')
|
||||
->addConstraint('BookOutline', []);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -437,7 +438,7 @@ function template_preprocess_book_navigation(&$variables) {
|
||||
}
|
||||
|
||||
if (!empty($build)) {
|
||||
drupal_render($build);
|
||||
\Drupal::service('renderer')->render($build);
|
||||
}
|
||||
|
||||
$variables['has_links'] = FALSE;
|
||||
|
||||
@@ -33,6 +33,13 @@ content:
|
||||
weight: 15
|
||||
region: content
|
||||
third_party_settings: { }
|
||||
status:
|
||||
type: boolean_checkbox
|
||||
settings:
|
||||
display_label: true
|
||||
weight: 120
|
||||
region: content
|
||||
third_party_settings: { }
|
||||
sticky:
|
||||
type: boolean_checkbox
|
||||
settings:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user