Unverified Commit 3c82d71d authored by alexpott's avatar alexpott

Issue #2935255 by Jo Fitzgerald, kim.pepper, voleger, alexpott, martin107,...

Issue #2935255 by Jo Fitzgerald, kim.pepper, voleger, alexpott, martin107, jibran, catch: Remove all usages of drupal_get_message and drupal_set_message in core lib
parent 07df2282
......@@ -2426,7 +2426,8 @@ function hook_validation_constraint_alter(array &$definitions) {
* markup or a set of Ajax commands. If you choose to return HTML markup, you
* can return it as a string or a renderable array, and it will be placed in
* the defined 'wrapper' element (see documentation above in @ref sub_form).
* In addition, any messages returned by drupal_get_messages(), themed as in
* In addition, any messages returned by
* \Drupal\Core\Messenger\Messenger::all(), themed as in
* status-messages.html.twig, will be prepended.
*
* To return commands, you need to set up an object of class
......
......@@ -1004,7 +1004,7 @@ services:
- { name: event_subscriber }
form_ajax_subscriber:
class: Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber
arguments: ['@form_ajax_response_builder', '@string_translation']
arguments: ['@form_ajax_response_builder', '@string_translation', '@messenger']
tags:
- { name: event_subscriber }
route_enhancer.param_conversion:
......
......@@ -4,6 +4,7 @@
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Plugin\ContextAwarePluginAssignmentTrait;
use Drupal\Core\Plugin\ContextAwarePluginBase;
use Drupal\Component\Utility\Unicode;
......@@ -26,6 +27,7 @@
abstract class BlockBase extends ContextAwarePluginBase implements BlockPluginInterface, PluginWithFormsInterface {
use ContextAwarePluginAssignmentTrait;
use MessengerTrait;
use PluginWithFormsTrait;
/**
......
......@@ -5,8 +5,7 @@
/**
* The interface for "messages" (#type => status_messages) blocks.
*
* @see drupal_set_message()
* @see drupal_get_message()
* @see \Drupal\Core\Messenger\MessengerInterface
* @see \Drupal\Core\Render\Element\StatusMessages
* @see \Drupal\block\Plugin\DisplayVariant\BlockPageVariant
*
......
......@@ -73,7 +73,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirectUrl($this->getRedirectUrl());
}
drupal_set_message($this->getDeletionMessage());
$this->messenger()->addStatus($this->getDeletionMessage());
$this->logDeletionMessage();
}
......
......@@ -120,7 +120,7 @@ protected function logDeletionMessage() {
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->getEntity()->delete();
drupal_set_message($this->getDeletionMessage());
$this->messenger()->addStatus($this->getDeletionMessage());
$form_state->setRedirectUrl($this->getCancelUrl());
$this->logDeletionMessage();
}
......
......@@ -2,6 +2,7 @@
namespace Drupal\Core\Entity;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Routing\RedirectDestinationTrait;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
......@@ -13,6 +14,7 @@
*/
class EntityListBuilder extends EntityHandlerBase implements EntityListBuilderInterface, EntityHandlerInterface {
use MessengerTrait;
use RedirectDestinationTrait;
/**
......
......@@ -52,7 +52,7 @@ public function getFormId() {
public function buildForm(array $form, FormStateInterface $form_state) {
// Get all the available ways to transfer files.
if (empty($_SESSION['authorize_filetransfer_info'])) {
drupal_set_message($this->t('Unable to continue, no available methods of file transfer'), 'error');
$this->messenger()->addError($this->t('Unable to continue, no available methods of file transfer'));
return [];
}
$available_backends = $_SESSION['authorize_filetransfer_info'];
......
......@@ -9,6 +9,7 @@
use Drupal\Core\Form\FormAjaxException;
use Drupal\Core\Form\FormAjaxResponseBuilderInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
......@@ -30,6 +31,13 @@ class FormAjaxSubscriber implements EventSubscriberInterface {
*/
protected $formAjaxResponseBuilder;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a new FormAjaxSubscriber.
*
......@@ -37,10 +45,13 @@ class FormAjaxSubscriber implements EventSubscriberInterface {
* The form AJAX response builder.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(FormAjaxResponseBuilderInterface $form_ajax_response_builder, TranslationInterface $string_translation) {
public function __construct(FormAjaxResponseBuilderInterface $form_ajax_response_builder, TranslationInterface $string_translation, MessengerInterface $messenger) {
$this->formAjaxResponseBuilder = $form_ajax_response_builder;
$this->stringTranslation = $string_translation;
$this->messenger = $messenger;
}
/**
......@@ -75,7 +86,7 @@ public function onException(GetResponseForExceptionEvent $event) {
// Render a nice error message in case we have a file upload which exceeds
// the configured upload limit.
if ($exception instanceof BrokenPostRequestException && $request->query->has(FormBuilderInterface::AJAX_FORM_REQUEST)) {
$this->drupalSetMessage($this->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', ['@size' => $this->formatSize($exception->getSize())]), 'error');
$this->messenger->addError($this->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', ['@size' => $this->formatSize($exception->getSize())]));
$response = new AjaxResponse(NULL, 200);
$status_messages = ['#type' => 'status_messages'];
$response->addCommand(new PrependCommand(NULL, $status_messages));
......@@ -154,13 +165,4 @@ public static function getSubscribedEvents() {
return $events;
}
/**
* Wraps drupal_set_message().
*
* @codeCoverageIgnore
*/
protected function drupalSetMessage($message = NULL, $type = 'status', $repeat = FALSE) {
drupal_set_message($message, $type, $repeat);
}
}
......@@ -121,7 +121,7 @@ function callback_batch_finished($success, $results, $operations) {
'#items' => $results,
];
$message .= drupal_render($list);
drupal_set_message($message);
\Drupal::messenger()->addStatus($message);
}
else {
// An error occurred.
......@@ -131,7 +131,7 @@ function callback_batch_finished($success, $results, $operations) {
'%error_operation' => $error_operation[0],
'@arguments' => print_r($error_operation[1], TRUE)
]);
drupal_set_message($message, 'error');
\Drupal::messenger()->addError($message);
}
}
......
......@@ -135,7 +135,7 @@ public function buildForm(array $form, FormStateInterface $form_state) {
// successfully.)
$post_params = $this->getRequest()->request->all();
if (empty($post_params) && (Settings::get('skip_permissions_hardening') || !drupal_verify_install_file($this->root . '/' . $settings_file, FILE_EXIST | FILE_READABLE | FILE_NOT_WRITABLE) || !drupal_verify_install_file($this->root . '/' . $settings_dir, FILE_NOT_WRITABLE, 'dir'))) {
drupal_set_message(t('All necessary changes to %dir and %file have been made, so you should remove write permissions to them now in order to avoid security risks. If you are unsure how to do so, consult the <a href=":handbook_url">online handbook</a>.', ['%dir' => $settings_dir, '%file' => $settings_file, ':handbook_url' => 'https://www.drupal.org/server-permissions']), 'warning');
$this->messenger()->addWarning(t('All necessary changes to %dir and %file have been made, so you should remove write permissions to them now in order to avoid security risks. If you are unsure how to do so, consult the <a href=":handbook_url">online handbook</a>.', ['%dir' => $settings_dir, '%file' => $settings_file, ':handbook_url' => 'https://www.drupal.org/server-permissions']));
}
$form['#attached']['library'][] = 'system/drupal.system';
......
......@@ -5,6 +5,7 @@
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
......@@ -23,6 +24,7 @@
*/
class MailManager extends DefaultPluginManager implements MailManagerInterface {
use MessengerTrait;
use StringTranslationTrait;
/**
......@@ -303,7 +305,7 @@ public function doMail($module, $key, $to, $langcode, $params = [], $reply = NUL
'%to' => $message['to'],
'%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
]);
drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');
$this->messenger()->addError($this->t('Unable to send email. Contact the site administrator if the problem persists.'));
}
}
}
......
......@@ -3,6 +3,7 @@
namespace Drupal\Core\Plugin;
use Drupal\Component\Plugin\PluginBase as ComponentPluginBase;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
......@@ -14,5 +15,6 @@
abstract class PluginBase extends ComponentPluginBase {
use StringTranslationTrait;
use DependencySerializationTrait;
use MessengerTrait;
}
......@@ -5,7 +5,7 @@
/**
* Provides a messages element.
*
* Used to display results of drupal_set_message() calls.
* Used to display results of \Drupal::messenger()->addMessage() calls.
*
* Usage example:
* @code
......@@ -61,7 +61,8 @@ public static function generatePlaceholder(array $element) {
*
* @param string|null $type
* Limit the messages returned by type. Defaults to NULL, meaning all types.
* Passed on to drupal_get_messages(). These values are supported:
* Passed on to \Drupal\Core\Messenger\Messenger::deleteByType(). These
* values are supported:
* - NULL
* - 'status'
* - 'warning'
......@@ -72,9 +73,15 @@ public static function generatePlaceholder(array $element) {
*
* @see drupal_get_messages()
*/
public static function renderMessages($type) {
public static function renderMessages($type = NULL) {
$render = [];
$messages = drupal_get_messages($type);
if (isset($type)) {
$messages = \Drupal::messenger()->deleteByType($type);
}
else {
$messages = \Drupal::messenger()->deleteAll();
}
if ($messages) {
// Render the messages.
$render = [
......
......@@ -649,8 +649,8 @@ protected function replacePlaceholders(array &$elements) {
// 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\Messenger 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.
......
......@@ -3,7 +3,6 @@
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;
......@@ -20,8 +19,6 @@
*/
class TestContextAwareBlock extends BlockBase {
use MessengerTrait;
/**
* {@inheritdoc}
*/
......
......@@ -3,7 +3,6 @@
namespace Drupal\views_test_data\Plugin\views\field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;
use Drupal\views\ResultRow;
......@@ -17,7 +16,6 @@
*/
class FieldFormButtonTest extends FieldPluginBase {
use MessengerTrait;
use UncacheableFieldHandlerTrait;
/**
......
......@@ -125,8 +125,8 @@
echo "\nEnvironment cleaned.\n";
// Get the status messages and print them.
$messages = drupal_get_messages('status');
foreach ($messages['status'] as $text) {
$messages = \Drupal::messenger()->messagesByType('status');
foreach ($messages as $text) {
echo " - " . $text . "\n";
}
exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
......
......@@ -6,12 +6,16 @@
/**
* @covers ::drupal_set_message
* @group PHPUnit
* @group Common
* @group legacy
*/
class DrupalSetMessageTest extends KernelTestBase {
/**
* The basic functionality of drupal_set_message().
*
* @expectedDeprecation drupal_set_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead. See https://www.drupal.org/node/2774931
* @expectedDeprecation drupal_get_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::all() or \Drupal\Core\Messenger\MessengerInterface::messagesByType() instead. See https://www.drupal.org/node/2774931
*/
public function testDrupalSetMessage() {
drupal_set_message(t('A message: @foo', ['@foo' => 'bar']));
......
......@@ -38,7 +38,8 @@ public function testMunging() {
// Disable insecure uploads.
$this->config('system.file')->set('allow_insecure_uploads', 0)->save();
$munged_name = file_munge_filename($this->name, '', TRUE);
$messages = drupal_get_messages();
$messages = \Drupal::messenger()->all();
\Drupal::messenger()->deleteAll();
$this->assertTrue(in_array(strtr('For security reasons, your upload has been renamed to <em class="placeholder">%filename</em>.', ['%filename' => $munged_name]), $messages['status']), 'Alert properly set when a file is renamed.');
$this->assertNotEqual($munged_name, $this->name, format_string('The new filename (%munged) has been modified from the original (%original)', ['%munged' => $munged_name, '%original' => $this->name]));
}
......
......@@ -80,7 +80,8 @@ public function testLimitValidationErrors() {
$form_builder = $this->container->get('form_builder');
$form_builder->submitForm($this, $form_state);
$messages = drupal_get_messages();
$messages = \Drupal::messenger()->all();
\Drupal::messenger()->deleteAll();
$this->assertTrue(isset($messages['error']));
$error_messages = $messages['error'];
$this->assertEqual($error_messages[0], 'Three field is required.');
......
......@@ -24,8 +24,8 @@ public function testMessages() {
\Drupal::service('theme_handler')->install(['classy']);
$this->config('system.theme')->set('default', 'classy')->save();
drupal_set_message('An error occurred', 'error');
drupal_set_message('But then something nice happened');
\Drupal::messenger()->addError('An error occurred');
\Drupal::messenger()->addStatus('But then something nice happened');
$messages = [
'#type' => 'status_messages',
];
......
......@@ -8,6 +8,7 @@
use Drupal\Core\Form\FormAjaxException;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
......@@ -43,6 +44,13 @@ class FormAjaxSubscriberTest extends UnitTestCase {
*/
protected $stringTranslation;
/**
* The mocked messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $messenger;
/**
* {@inheritdoc}
*/
......@@ -52,7 +60,8 @@ protected function setUp() {
$this->httpKernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
$this->formAjaxResponseBuilder = $this->getMock('Drupal\Core\Form\FormAjaxResponseBuilderInterface');
$this->stringTranslation = $this->getStringTranslationStub();
$this->subscriber = new FormAjaxSubscriber($this->formAjaxResponseBuilder, $this->stringTranslation);
$this->messenger = $this->createMock(MessengerInterface::class);
$this->subscriber = new FormAjaxSubscriber($this->formAjaxResponseBuilder, $this->stringTranslation, $this->messenger);
}
/**
......@@ -147,13 +156,19 @@ public function testOnExceptionResponseBuilderException() {
public function testOnExceptionBrokenPostRequest() {
$this->formAjaxResponseBuilder->expects($this->never())
->method('buildResponse');
$this->messenger->expects($this->once())
->method('addError');
$this->subscriber = $this->getMockBuilder('\Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber')
->setConstructorArgs([$this->formAjaxResponseBuilder, $this->getStringTranslationStub()])
->setMethods(['drupalSetMessage', 'formatSize'])
->setConstructorArgs([
$this->formAjaxResponseBuilder,
$this->getStringTranslationStub(),
$this->messenger,
])
->setMethods(['formatSize'])
->getMock();
$this->subscriber->expects($this->once())
->method('drupalSetMessage')
->willReturn('asdf');
$this->subscriber->expects($this->once())
->method('formatSize')
->with(32 * 1e6)
......
......@@ -165,8 +165,6 @@ public static function getSkippedDeprecations() {
'Automatically creating the first item for computed fields is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0. Use \Drupal\Core\TypedData\ComputedItemListTrait instead.',
'"\Drupal\Core\Entity\ContentEntityStorageBase::doLoadRevisionFieldItems()" is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0. "\Drupal\Core\Entity\ContentEntityStorageBase::doLoadMultipleRevisionsFieldItems()" should be implemented instead. See https://www.drupal.org/node/2924915.',
'Passing a single revision ID to "\Drupal\Core\Entity\Sql\SqlContentEntityStorage::buildQuery()" is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0. An array of revision IDs should be given instead. See https://www.drupal.org/node/2924915.',
'drupal_set_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::addMessage() instead. See https://www.drupal.org/node/2774931',
'drupal_get_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \Drupal\Core\Messenger\MessengerInterface::all() or \Drupal\Core\Messenger\MessengerInterface::messagesByType() instead. See https://www.drupal.org/node/2774931',
'Adding or retrieving messages prior to the container being initialized was deprecated in Drupal 8.5.0 and this functionality will be removed before Drupal 9.0.0. Please report this usage at https://www.drupal.org/node/2928994.',
'The "serializer.normalizer.file_entity.hal" normalizer service is deprecated: it is obsolete, it only remains available for backwards compatibility.',
'Drupal\comment\Plugin\Action\PublishComment is deprecated in Drupal 8.5.x, will be removed before Drupal 9.0.0. Use \Drupal\Core\Action\Plugin\Action\PublishAction instead. See https://www.drupal.org/node/2919303.',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment