Commit b84b827d authored by alexpott's avatar alexpott

Issue #2935256 by Jo Fitzgerald, voleger, kim.pepper, ibustos, Yogesh Pawar,...

Issue #2935256 by Jo Fitzgerald, voleger, kim.pepper, ibustos, Yogesh Pawar, catch, jibran: Remove all usages of drupal_get_message and drupal_set_message in modules
parent 52fdfaa5
......@@ -3,6 +3,7 @@
namespace Drupal\Core\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
......@@ -10,6 +11,7 @@
*/
abstract class ConfigFormBase extends FormBase {
use ConfigFormBaseTrait;
use MessengerTrait;
/**
* Constructs a \Drupal\system\ConfigFormBase object.
......@@ -51,7 +53,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
drupal_set_message($this->t('The configuration options have been saved.'));
$this->messenger()->addStatus($this->t('The configuration options have been saved.'));
}
}
......@@ -3,6 +3,7 @@
namespace Drupal\Core\Form;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Render\Element;
/**
......@@ -10,6 +11,8 @@
*/
class FormErrorHandler implements FormErrorHandlerInterface {
use MessengerTrait;
/**
* {@inheritdoc}
*/
......@@ -39,7 +42,7 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st
// Loop through all form errors and set an error message.
foreach ($errors as $error) {
$this->drupalSetMessage($error, 'error');
$this->messenger()->addMessage($error, 'error');
}
}
......@@ -54,6 +57,7 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st
* Grouping example:
* Assume you have a 'street' element somewhere in a form, which is displayed
* in a details element 'address'. It might be:
*
* @code
* $form['street'] = [
* '#type' => 'textfield',
......@@ -160,13 +164,4 @@ protected function setElementErrorsFromFormState(array &$form, FormStateInterfac
$elements['#errors'] = $form_state->getError($elements);
}
/**
* Wraps drupal_set_message().
*
* @codeCoverageIgnore
*/
protected function drupalSetMessage($message = NULL, $type = 'status', $repeat = FALSE) {
drupal_set_message($message, $type, $repeat);
}
}
......@@ -132,7 +132,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
*/
public function save(array $form, FormStateInterface $form_state) {
$this->entity->save();
drupal_set_message($this->t('The action has been successfully saved.'));
$this->messenger()->addStatus($this->t('The action has been successfully saved.'));
$form_state->setRedirect('entity.action.collection');
}
......
......@@ -5,6 +5,7 @@
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\ConfigurableActionBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Session\AccountInterface;
......@@ -36,6 +37,13 @@ class MessageAction extends ConfigurableActionBase implements ContainerFactoryPl
*/
protected $renderer;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a MessageAction object.
*
......@@ -49,19 +57,22 @@ class MessageAction extends ConfigurableActionBase implements ContainerFactoryPl
* The token service.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token, RendererInterface $renderer) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token, RendererInterface $renderer, MessengerInterface $messenger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->token = $token;
$this->renderer = $renderer;
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container->get('token'), $container->get('renderer'));
return new static($configuration, $plugin_id, $plugin_definition, $container->get('token'), $container->get('renderer'), $container->get('messenger'));
}
/**
......@@ -77,7 +88,7 @@ public function execute($entity = NULL) {
];
// @todo Fix in https://www.drupal.org/node/2577827
drupal_set_message($this->renderer->renderPlain($build));
$this->messenger->addStatus($this->renderer->renderPlain($build));
}
/**
......
......@@ -22,12 +22,12 @@ public function save(array $form, FormStateInterface $form_state) {
$label = $feed->label();
$view_link = $feed->link($label, 'canonical');
if ($status == SAVED_UPDATED) {
drupal_set_message($this->t('The feed %feed has been updated.', ['%feed' => $view_link]));
$this->messenger()->addStatus($this->t('The feed %feed has been updated.', ['%feed' => $view_link]));
$form_state->setRedirectUrl($feed->urlInfo('canonical'));
}
else {
$this->logger('aggregator')->notice('Feed %feed added.', ['%feed' => $feed->label(), 'link' => $this->l($this->t('View'), new Url('aggregator.admin_overview'))]);
drupal_set_message($this->t('The feed %feed has been added.', ['%feed' => $view_link]));
$this->messenger()->addStatus($this->t('The feed %feed has been added.', ['%feed' => $view_link]));
}
}
......
......@@ -123,14 +123,14 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
}
catch (RequestException $e) {
$this->logger('aggregator')->warning('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]);
drupal_set_message($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]));
$this->messenger()->addStatus($this->t('Failed to download OPML file due to "%error".', ['%error' => $e->getMessage()]));
return;
}
}
$feeds = $this->parseOpml($data);
if (empty($feeds)) {
drupal_set_message($this->t('No new feed has been added.'));
$this->messenger()->addStatus($this->t('No new feed has been added.'));
return;
}
......@@ -138,7 +138,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
foreach ($feeds as $feed) {
// Ensure URL is valid.
if (!UrlHelper::isValid($feed['url'], TRUE)) {
drupal_set_message($this->t('The URL %url is invalid.', ['%url' => $feed['url']]), 'warning');
$this->messenger()->addWarning($this->t('The URL %url is invalid.', ['%url' => $feed['url']]));
continue;
}
......@@ -153,11 +153,11 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
$result = $this->feedStorage->loadMultiple($ids);
foreach ($result as $old) {
if (strcasecmp($old->label(), $feed['title']) == 0) {
drupal_set_message($this->t('A feed named %title already exists.', ['%title' => $old->label()]), 'warning');
$this->messenger()->addWarning($this->t('A feed named %title already exists.', ['%title' => $old->label()]));
continue 2;
}
if (strcasecmp($old->getUrl(), $feed['url']) == 0) {
drupal_set_message($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]), 'warning');
$this->messenger()->addWarning($this->t('A feed with the URL %url already exists.', ['%url' => $old->getUrl()]));
continue 2;
}
}
......
......@@ -6,6 +6,7 @@
use Drupal\aggregator\FeedInterface;
use Drupal\Component\Datetime\DateTimePlus;
use Drupal\Core\Http\ClientFactory;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
......@@ -42,6 +43,13 @@ class DefaultFetcher implements FetcherInterface, ContainerFactoryPluginInterfac
*/
protected $logger;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a DefaultFetcher object.
*
......@@ -49,10 +57,13 @@ class DefaultFetcher implements FetcherInterface, ContainerFactoryPluginInterfac
* A Guzzle client object.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(ClientFactory $http_client_factory, LoggerInterface $logger) {
public function __construct(ClientFactory $http_client_factory, LoggerInterface $logger, MessengerInterface $messenger) {
$this->httpClientFactory = $http_client_factory;
$this->logger = $logger;
$this->messenger = $messenger;
}
/**
......@@ -61,7 +72,8 @@ public function __construct(ClientFactory $http_client_factory, LoggerInterface
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$container->get('http_client_factory'),
$container->get('logger.factory')->get('aggregator')
$container->get('logger.factory')->get('aggregator'),
$container->get('messenger')
);
}
......@@ -115,7 +127,7 @@ public function fetch(FeedInterface $feed) {
}
catch (RequestException $e) {
$this->logger->warning('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]);
drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]), 'warning');
$this->messenger->addWarning(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]));
return FALSE;
}
}
......
......@@ -4,6 +4,7 @@
use Drupal\aggregator\Plugin\ParserInterface;
use Drupal\aggregator\FeedInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Zend\Feed\Reader\Reader;
use Zend\Feed\Reader\Exception\ExceptionInterface;
......@@ -20,6 +21,8 @@
*/
class DefaultParser implements ParserInterface {
use MessengerTrait;
/**
* {@inheritdoc}
*/
......@@ -31,7 +34,7 @@ public function parse(FeedInterface $feed) {
}
catch (ExceptionInterface $e) {
watchdog_exception('aggregator', $e);
drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]), 'error');
$this->messenger()->addError(t('The feed from %site seems to be broken because of error "%error".', ['%site' => $feed->label(), '%error' => $e->getMessage()]));
return FALSE;
}
......
......@@ -3,15 +3,16 @@
namespace Drupal\aggregator\Plugin\aggregator\processor;
use Drupal\aggregator\Entity\Item;
use Drupal\aggregator\FeedInterface;
use Drupal\aggregator\ItemStorageInterface;
use Drupal\aggregator\Plugin\AggregatorPluginSettingsBase;
use Drupal\aggregator\Plugin\ProcessorInterface;
use Drupal\aggregator\FeedInterface;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Form\ConfigFormBaseTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\UrlGeneratorTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -28,6 +29,7 @@
* )
*/
class DefaultProcessor extends AggregatorPluginSettingsBase implements ProcessorInterface, ContainerFactoryPluginInterface {
use ConfigFormBaseTrait;
use UrlGeneratorTrait;
......@@ -52,6 +54,13 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
*/
protected $dateFormatter;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a DefaultProcessor object.
*
......@@ -67,11 +76,14 @@ class DefaultProcessor extends AggregatorPluginSettingsBase implements Processor
* The entity storage for feed items.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, ItemStorageInterface $item_storage, DateFormatterInterface $date_formatter) {
public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config, ItemStorageInterface $item_storage, DateFormatterInterface $date_formatter, MessengerInterface $messenger) {
$this->configFactory = $config;
$this->itemStorage = $item_storage;
$this->dateFormatter = $date_formatter;
$this->messenger = $messenger;
// @todo Refactor aggregator plugins to ConfigEntity so merging
// the configuration here is not needed.
parent::__construct($configuration + $this->getConfiguration(), $plugin_id, $plugin_definition);
......@@ -87,7 +99,8 @@ public static function create(ContainerInterface $container, array $configuratio
$plugin_definition,
$container->get('config.factory'),
$container->get('entity_type.manager')->getStorage('aggregator_item'),
$container->get('date.formatter')
$container->get('date.formatter'),
$container->get('messenger')
);
}
......@@ -231,7 +244,7 @@ public function delete(FeedInterface $feed) {
$this->itemStorage->delete($items);
}
// @todo This should be moved out to caller with a different message maybe.
drupal_set_message(t('The news items from %site have been deleted.', ['%site' => $feed->label()]));
$this->messenger->addStatus(t('The news items from %site have been deleted.', ['%site' => $feed->label()]));
}
/**
......
......@@ -4,6 +4,7 @@
use Drupal\aggregator\Form\SettingsForm;
use Drupal\Core\Form\FormState;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Tests\UnitTestCase;
/**
......@@ -55,6 +56,10 @@ protected function setUp() {
->will($this->returnValue(['aggregator_test' => ['title' => '', 'description' => '']]));
}
/** @var \Drupal\Core\Messenger\MessengerInterface|\PHPUnit_Framework_MockObject_MockBuilder $messenger */
$messenger = $this->createMock(MessengerInterface::class);
$messenger->expects($this->any())->method('addMessage');
$this->settingsForm = new SettingsForm(
$this->configFactory,
$this->managers['fetcher'],
......@@ -62,6 +67,7 @@ protected function setUp() {
$this->managers['processor'],
$this->getStringTranslationStub()
);
$this->settingsForm->setMessenger($messenger);
}
/**
......@@ -104,11 +110,3 @@ public function testSettingsForm() {
}
}
// @todo Delete after https://www.drupal.org/node/2278383 is in.
namespace Drupal\Core\Form;
if (!function_exists('drupal_set_message')) {
function drupal_set_message() {
}
}
......@@ -120,7 +120,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
public function submitForm(array &$form, FormStateInterface $form_state) {
$ip = trim($form_state->getValue('ip'));
$this->ipManager->banIp($ip);
drupal_set_message($this->t('The IP address %ip has been banned.', ['%ip' => $ip]));
$this->messenger()->addStatus($this->t('The IP address %ip has been banned.', ['%ip' => $ip]));
$form_state->setRedirect('ban.admin_page');
}
......
......@@ -96,7 +96,7 @@ public function buildForm(array $form, FormStateInterface $form_state, $ban_id =
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->ipManager->unbanIp($this->banIp);
$this->logger('user')->notice('Deleted %ip', ['%ip' => $this->banIp]);
drupal_set_message($this->t('The IP address %ip was deleted.', ['%ip' => $this->banIp]));
$this->messenger()->addStatus($this->t('The IP address %ip was deleted.', ['%ip' => $this->banIp]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
......
......@@ -730,8 +730,8 @@ protected function getPlaceholderOrder($html, $placeholders) {
// being rendered: any code can add messages to render.
// This violates the principle that each lazy builder must be able to render
// itself in isolation, and therefore in any order. However, we cannot
// change the way drupal_set_message() works in the Drupal 8 cycle. So we
// have to accommodate its special needs.
// change the way \Drupal\Core\Messenger\MessengerInterface::addMessage()
// works in the Drupal 8 cycle. So we have to accommodate its special needs.
// Allowing placeholders to be rendered in a particular order (in this case:
// last) would violate this isolation principle. Thus a monopoly is granted
// to this one special case, with this hard-coded solution.
......
......@@ -24,7 +24,7 @@ public function test() {
if ($has_session) {
// Only set a message if a session already exists, otherwise we always
// trigger a session, which means we can't test no-session requests.
drupal_set_message('Hello from BigPipe!');
\Drupal::messenger()->addStatus('Hello from BigPipe!');
}
$build['html'] = $cases['html']->renderArray;
......
......@@ -145,7 +145,11 @@ function block_rebuild() {
// Disable blocks in invalid regions.
if (!isset($regions[$block->getRegion()])) {
if ($block->status()) {
drupal_set_message(t('The block %info was assigned to the invalid region %region and has been disabled.', ['%info' => $block_id, '%region' => $block->getRegion()]), 'warning');
\Drupal::messenger()
->addWarning(t('The block %info was assigned to the invalid region %region and has been disabled.', [
'%info' => $block_id,
'%region' => $block->getRegion(),
]));
}
$block
->setRegion(system_default_region($theme))
......
......@@ -360,7 +360,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
// Save the settings of the plugin.
$entity->save();
drupal_set_message($this->t('The block configuration has been saved.'));
$this->messenger()->addStatus($this->t('The block configuration has been saved.'));
$form_state->setRedirect(
'block.admin_display_theme',
[
......
......@@ -11,6 +11,7 @@
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -56,6 +57,13 @@ class BlockListBuilder extends ConfigEntityListBuilder implements FormInterface
*/
protected $limit = FALSE;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a new BlockListBuilder object.
*
......@@ -68,11 +76,12 @@ class BlockListBuilder extends ConfigEntityListBuilder implements FormInterface
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ThemeManagerInterface $theme_manager, FormBuilderInterface $form_builder) {
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ThemeManagerInterface $theme_manager, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
parent::__construct($entity_type, $storage);
$this->themeManager = $theme_manager;
$this->formBuilder = $form_builder;
$this->messenger = $messenger;
}
/**
......@@ -83,7 +92,8 @@ public static function createInstance(ContainerInterface $container, EntityTypeI
$entity_type,
$container->get('entity.manager')->getStorage($entity_type->id()),
$container->get('theme.manager'),
$container->get('form_builder')
$container->get('form_builder'),
$container->get('messenger')
);
}
......@@ -367,7 +377,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
$entity->setRegion($entity_values['region']);
$entity->save();
}
drupal_set_message(t('The block settings have been updated.'));
$this->messenger->addStatus($this->t('The block settings have been updated.'));
// Remove any previously set block placement.
$this->request->query->remove('block-placement');
......
......@@ -53,7 +53,7 @@ public static function create(ContainerInterface $container) {
*/
public function performOperation(BlockInterface $block, $op) {
$block->$op()->save();
drupal_set_message($this->t('The block settings have been updated.'));
$this->messenger()->addStatus($this->t('The block settings have been updated.'));
return $this->redirect('block.admin_display');
}
......
......@@ -17,7 +17,8 @@ public function testMultipleForms() {
'form2' => $this->formBuilder()->buildForm('\Drupal\block_test\Form\FavoriteAnimalTestForm', $form_state),
];
// Output all attached placeholders trough drupal_set_message(), so we can
// Output all attached placeholders trough
// \Drupal\Core\Messenger\MessengerInterface::addMessage(), so we can
// see if there's only one in the tests.
$post_render_callable = function ($elements) {
$matches = [];
......@@ -26,7 +27,7 @@ public function testMultipleForms() {
$action_values = $matches[2];
foreach ($action_values as $action_value) {
drupal_set_message('Form action: ' . $action_value);
$this->messenger()->addStatus('Form action: ' . $action_value);
}
return $elements;
};
......
......@@ -40,7 +40,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
drupal_set_message($this->t('Your favorite animal is: @favorite_animal', ['@favorite_animal' => $form['favorite_animal']['#value']]));
$this->messenger()->addStatus($this->t('Your favorite animal is: @favorite_animal', ['@favorite_animal' => $form['favorite_animal']['#value']]));
}
}
......@@ -49,7 +49,7 @@ public function validateForm(array &$form, FormStateInterface $form_state) {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
drupal_set_message($this->t('Your email address is @email', ['@email' => $form['email']['#value']]));
$this->messenger()->addStatus($this->t('Your email address is @email', ['@email' => $form['email']['#value']]));
}
}
......@@ -3,6 +3,7 @@
namespace Drupal\block_test\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;
......@@ -19,6 +20,8 @@
*/
class TestContextAwareBlock extends BlockBase {
use MessengerTrait;
/**
* {@inheritdoc}
*/
......@@ -37,7 +40,7 @@ public function build() {
*/
protected function blockAccess(AccountInterface $account) {
if ($this->getContextValue('user') instanceof UserInterface) {
drupal_set_message('User context found.');
$this->messenger()->addStatus('User context found.');
}
return parent::blockAccess($account);
......
......@@ -47,7 +47,8 @@ public static function setUpBeforeClass() {
*/
public function testRebuildNoBlocks() {
block_rebuild();
$messages = drupal_get_messages();
$messages = \Drupal::messenger()->all();
\Drupal::messenger()->deleteAll();
$this->assertEquals([], $messages);
}
......@@ -58,7 +59,8 @@ public function testRebuildNoInvalidBlocks() {
$this->placeBlock('system_powered_by_block', ['region' => 'content']);
block_rebuild();
$messages = drupal_get_messages();
$messages = \Drupal::messenger()->all();
\Drupal::messenger()->deleteAll();
$this->assertEquals([], $messages);