Skip to content

Latest commit

 

History

History
1166 lines (779 loc) · 30.2 KB

rules_overview.md

File metadata and controls

1166 lines (779 loc) · 30.2 KB

55 Rules Overview


Categories


Drupal10

AnnotationToAttributeRector

Change annotations with value to attribute

🔧 configure it!

 namespace Drupal\Core\Action\Plugin\Action;

+use Drupal\Core\Action\Plugin\Action\Derivative\EntityPublishedActionDeriver;
+use Drupal\Core\Action\Attribute\Action;
 use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\StringTranslation\TranslatableMarkup;

 /**
  * Publishes an entity.
- *
- * @Action(
- *   id = "entity:publish_action",
- *   action_label = @Translation("Publish"),
- *   deriver = "Drupal\Core\Action\Plugin\Action\Derivative\EntityPublishedActionDeriver",
- * )
  */
+#[Action(
+  id: 'entity:publish_action',
+  action_label: new TranslatableMarkup('Publish'),
+  deriver: EntityPublishedActionDeriver::class
+)]
 class PublishAction extends EntityActionBase {

SystemTimeZonesRector

Fixes deprecated system_time_zones() calls

🔧 configure it!

-system_time_zones();
-system_time_zones(FALSE, TRUE);
-system_time_zones(NULL, FALSE);
-system_time_zones(TRUE, FALSE);
+\Drupal\Core\Datetime\TimeZoneFormHelper::getOptionsList();
+\Drupal\Core\Datetime\TimeZoneFormHelper::getOptionsListByRegion();
+\Drupal\Core\Datetime\TimeZoneFormHelper::getOptionsList(NULL);
+\Drupal\Core\Datetime\TimeZoneFormHelper::getOptionsList(TRUE);

VersionedFunctionToServiceRector

Fixes deprecated function to service calls, used in Drupal 8 and 9 deprecations

🔧 configure it!

-_drupal_flush_css_js();
+\Drupal::service('asset.query_string')->reset();

WatchdogExceptionRector

Fixes deprecated watchdog_exception('update', $exception) calls

🔧 configure it!

-watchdog_exception('update', $exception);
+use \Drupal\Core\Utility\Error;
+$logger = \Drupal::logger('update');
+Error::logException($logger, $exception);

Drupal8

DBRector

Fixes deprecated db_delete() calls

🔧 configure it!

-db_delete($table, $options);
+\Drupal::database()->delete($table, $options);

-db_insert($table, $options);
+\Drupal::database()->insert($table, $options);

-db_query($query, $args, $options);
+\Drupal::database()->query($query, $args, $options);

-db_select($table, $alias, $options);
+\Drupal::database()->select($table, $alias, $options);

-db_update($table, $options);
+\Drupal::database()->update($table, $options);

DrupalLRector

Fixes deprecated \Drupal::l() calls

-\Drupal::l('User Login', \Drupal\Core\Url::fromRoute('user.login'));
+\Drupal\Core\Link::fromTextAndUrl('User Login', \Drupal\Core\Url::fromRoute('user.login'));

DrupalServiceRenameRector

Renames the IDs in Drupal::service() calls

🔧 configure it!

-\Drupal::service('old')->foo();
+\Drupal::service('bar')->foo();

DrupalSetMessageRector

Fixes deprecated drupal_set_message() calls

-drupal_set_message('example status', 'status');
+\Drupal::messenger()->addStatus('example status');

DrupalURLRector

Fixes deprecated \Drupal::url() calls

-\Drupal::url('user.login');
+\Drupal\Core\Url::fromRoute('user.login')->toString();

EntityCreateRector

Fixes deprecated entity_create() calls

-entity_create('node', ['bundle' => 'page', 'title' => 'Hello world']);
+\Drupal::service('entity_type.manager)->getStorage('node')->create(['bundle' => 'page', 'title' => 'Hello world']);

EntityDeleteMultipleRector

Fixes deprecated entity_delete_multiple() calls

-entity_delete_multiple('node', [1, 2, 42]);
+\Drupal::service('entity_type.manager')->getStorage('node')->delete(\Drupal::service('entity_type.manager')->getStorage('node')->loadMultiple(1, 2, 42));

EntityInterfaceLinkRector

Fixes deprecated link() calls

-$url = $entity->link();
+$url = $entity->toLink()->toString();

EntityLoadRector

Fixes deprecated ENTITY_TYPE_load() or entity_load() use

🔧 configure it!

-$entity = ENTITY_TYPE_load(123);
-$node = entity_load('node', 123);
+$entity = \Drupal::entityManager()->getStorage('ENTITY_TYPE')->load(123);
+$node = \Drupal::entityManager()->getStorage('node')->load(123);

EntityManagerRector

Fixes deprecated \Drupal::entityManager() calls

-$entity_manager = \Drupal::entityManager();
+$entity_manager = \Drupal::entityTypeManager();

EntityViewRector

Fixes deprecated entity_view() use

-$rendered = entity_view($entity, 'default');
+$rendered = \Drupal::entityTypeManager()->getViewBuilder($entity
+  ->getEntityTypeId())->view($entity, 'default');

FileDefaultSchemeRector

Fixes deprecated file_default_scheme calls

-$file_default_scheme = file_default_scheme();
+$file_default_scheme = \Drupal::config('system.file')->get('default_scheme');

FunctionalTestDefaultThemePropertyRector

Adds $defaultTheme property to Functional and FunctionalJavascript tests which do not have them.

 class SomeClassTest {
+  protected $defaultTheme = 'stark'
 }

GetMockRector

Fixes deprecated getMock() calls

🔧 configure it!

-$this->entityTypeManager = $this->getMock(EntityTypeManagerInterface::class);
+$this->entityTypeManager = $this->createMock(EntityTypeManagerInterface::class);

LinkGeneratorTraitLRector

Fixes deprecated l() calls

-$this->l($text, $url);
+\Drupal\Core\Link::fromTextAndUrl($text, $url);

RequestTimeConstRector

Fixes deprecated REQUEST_TIME calls

-$request_time = REQUEST_TIME;
+$request_time = \Drupal::time()->getRequestTime();

SafeMarkupFormatRector

Fixes deprecated SafeMarkup::format() calls

-$safe_string_markup_object = \Drupal\Component\Utility\SafeMarkup::format('hello world');
+$safe_string_markup_object = new \Drupal\Component\Render\FormattableMarkup('hello world');

StaticToFunctionRector

Fixes deprecated \Drupal\Component\Utility\Unicode::strlen() calls

🔧 configure it!

-$length = \Drupal\Component\Utility\Unicode::strlen('example');
+$length = mb_strlen('example');

-$string = \Drupal\Component\Utility\Unicode::strtolower('example');
+$string = mb_strtolower('example');

-$string = \Drupal\Component\Utility\Unicode::substr('example', 0, 2);
+$string = mb_substr('example', 0, 2);

Drupal9

AssertFieldByIdRector

Fixes deprecated AssertLegacyTrait::assertFieldById() calls

-$this->assertFieldById('edit-name', NULL);
-    $this->assertFieldById('edit-name', 'Test name');
-    $this->assertFieldById('edit-description', NULL);
-    $this->assertFieldById('edit-description');
+$this->assertSession()->fieldExists('edit-name');
+    $this->assertSession()->fieldValueEquals('edit-name', 'Test name');
+    $this->assertSession()->fieldExists('edit-description');
+    $this->assertSession()->fieldValueEquals('edit-description', '');

AssertFieldByNameRector

Fixes deprecated AssertLegacyTrait::assertFieldByName() calls

-$this->assertFieldByName('field_name', 'expected_value');
-$this->assertFieldByName("field_name[0][value][date]", '', 'Date element found.');
-$this->assertFieldByName("field_name[0][value][time]", null, 'Time element found.');
+$this->assertSession()->fieldValueEquals('field_name', 'expected_value');
+$this->assertSession()->fieldValueEquals("field_name[0][value][date]", '');
+$this->assertSession()->fieldExists("field_name[0][value][time]");

AssertLegacyTraitRector

Fixes deprecated AssertLegacyTrait::METHOD() calls

🔧 configure it!

-$this->assertLinkByHref('user/1/translations');
+$this->assertSession()->linkByHrefExists('user/1/translations');

-$this->assertLink('Anonymous comment title');
+$this->assertSession()->linkExists('Anonymous comment title');

-$this->assertNoEscaped('<div class="escaped">');
+$this->assertSession()->assertNoEscaped('<div class="escaped">');

-$this->assertNoFieldChecked('edit-settings-view-mode', 'default');
+$this->assertSession()->checkboxNotChecked('edit-settings-view-mode', 'default');

-$this->assertNoField('files[upload]', 'Found file upload field.');
+$this->assertSession()->fieldNotExists('files[upload]', 'Found file upload field.');

-$this->assertNoLinkByHref('user/2/translations');
+$this->assertSession()->linkByHrefNotExists('user/2/translations');

-$this->assertNoLink('Anonymous comment title');
+$this->assertSession()->linkNotExists('Anonymous comment title');

-$this->assertNoOption('edit-settings-view-mode', 'default');
+$this->assertSession()->optionNotExists('edit-settings-view-mode', 'default');

-$this->assertNoPattern('|<h4[^>]*></h4>|', 'No empty H4 element found.');
+$this->assertSession()->responseNotMatches('|<h4[^>]*></h4>|', 'No empty H4 element found.');

-$this->assertPattern('|<h4[^>]*></h4>|', 'No empty H4 element found.');
+$this->assertSession()->responseMatches('|<h4[^>]*></h4>|', 'No empty H4 element found.');

-$this->assertNoRaw('bartik/logo.svg');
+$this->assertSession()->responseNotContains('bartik/logo.svg');

-$this->assertRaw('bartik/logo.svg');
+$this->assertSession()->responseContains('bartik/logo.svg');

AssertNoFieldByIdRector

Fixes deprecated AssertLegacyTrait::assertNoFieldById() calls

-$this->assertNoFieldById('name');
-    $this->assertNoFieldById('name', 'not the value');
-    $this->assertNoFieldById('notexisting', NULL);
+$this->assertSession()->assertNoFieldById('name');
+    $this->assertSession()->fieldValueNotEquals('name', 'not the value');
+    $this->assertSession()->fieldNotExists('notexisting');

AssertNoFieldByNameRector

Fixes deprecated AssertLegacyTrait::assertNoFieldByName() calls

-$this->assertNoFieldByName('name');
-    $this->assertNoFieldByName('name', 'not the value');
-    $this->assertNoFieldByName('notexisting');
-    $this->assertNoFieldByName('notexisting', NULL);
+$this->assertSession()->fieldValueNotEquals('name', '');
+    $this->assertSession()->fieldValueNotEquals('name', 'not the value');
+    $this->assertSession()->fieldValueNotEquals('notexisting', '');
+    $this->assertSession()->fieldNotExists('notexisting');

AssertNoUniqueTextRector

Fixes deprecated AssertLegacyTrait::assertNoUniqueText() calls

-$this->assertNoUniqueText('Duplicated message');
+$page_text = $this->getSession()->getPage()->getText();
+$nr_found = substr_count($page_text, 'Duplicated message');
+$this->assertGreaterThan(1, $nr_found, "'Duplicated message' found more than once on the page");

AssertOptionSelectedRector

Fixes deprecated AssertLegacyTrait::assertOptionSelected() calls

-$this->assertOptionSelected('options', 2);
+$this->assertTrue($this->assertSession()->optionExists('options', 2)->hasAttribute('selected'));

ConstructFieldXpathRector

Fixes deprecated AssertLegacyTrait::constructFieldXpath() calls

-$this->constructFieldXpath('id', 'edit-preferred-admin-langcode');
+$this->getSession()->getPage()->findField('edit-preferred-admin-langcode');

ExtensionPathRector

Fixes deprecated drupal_get_filename() calls

🔧 configure it!

-drupal_get_filename('module', 'node');
-drupal_get_filename('theme', 'seven');
-drupal_get_filename('profile', 'standard');
+\Drupal::service('extension.list.module')->getPathname('node');
+\Drupal::service('extension.list.theme')->getPathname('seven');
+\Drupal::service('extension.list.profile')->getPathname('standard');

-drupal_get_path('module', 'node');
-drupal_get_path('theme', 'seven');
-drupal_get_path('profile', 'standard');
+\Drupal::service('extension.list.module')->getPath('node');
+\Drupal::service('extension.list.theme')->getPath('seven');
+\Drupal::service('extension.list.profile')->getPath('standard');

FileBuildUriRector

Fixes deprecated file_build_uri() calls

-$uri1 = file_build_uri('path/to/file.txt');
+$uri1 = \Drupal::service('stream_wrapper_manager')->normalizeUri(\Drupal::config('system.file')->get('default_scheme') . ('://' . 'path/to/file.txt'));
 $path = 'path/to/other/file.png';
-$uri2 = file_build_uri($path);
+$uri2 = \Drupal::service('stream_wrapper_manager')->normalizeUri(\Drupal::config('system.file')->get('default_scheme') . ('://' . $path));

FileCreateUrlRector

Fixes deprecated file_create_url() calls

-file_create_url($uri);
+\Drupal::service('file_url_generator')->generateAbsoluteString($uri);

FileUrlTransformRelativeRector

Fixes deprecated file_url_transform_relative() calls

-file_url_transform_relative($uri);
+\Drupal::service('file_url_generator')->transformRelative($uri);

FromUriRector

Fixes deprecated file_create_url() calls from \Drupal\Core\Url::fromUri().

-\Drupal\Core\Url::fromUri(file_create_url($uri));
+\Drupal::service('file_url_generator')->generate($uri);

FunctionToEntityTypeStorageMethod

Refactor function call to an entity storage method

🔧 configure it!

-taxonomy_terms_static_reset();
+\Drupal::entityTypeManager()->getStorage('taxonomy_term')->resetCache();

-taxonomy_vocabulary_static_reset($vids);
+\Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->resetCache($vids);

FunctionToFirstArgMethodRector

Fixes deprecated taxonomy_implode_tags() calls

🔧 configure it!

-$url = taxonomy_term_uri($term);
-$name = taxonomy_term_title($term);
+$url = $term->toUrl();
+$name = $term->label();

GetAllOptionsRector

Fixes deprecated AssertLegacyTrait::getAllOptions() calls

 $this->drupalGet('/form-test/select');
-    $this->assertCount(6, $this->getAllOptions($this->cssSelect('select[name="opt_groups"]')[0]));
+    $this->assertCount(6, $this->cssSelect('select[name="opt_groups"]')[0]->findAll('xpath', '//option'));

GetRawContentRector

Fixes deprecated AssertLegacyTrait::getRawContent() calls

-$this->getRawContent();
+$this->getSession()->getPage()->getContent();

ModuleLoadRector

Fixes deprecated module_load_install() calls

-module_load_install('example');
+\Drupal::moduleHandler()->loadInclude('example', 'install');
 $type = 'install';
 $module = 'example';
 $name = 'name';
-module_load_include($type, $module, $name);
-module_load_include($type, $module);
+\Drupal::moduleHandler()->loadInclude($module, $type, $name);
+\Drupal::moduleHandler()->loadInclude($module, $type);

PassRector

Fixes deprecated AssertLegacyTrait::pass() calls

-// Check for pass
-$this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
+// Check for pass

ProtectedStaticModulesPropertyRector

"public static $modules" will have its visibility changed to protected.

 class SomeClassTest {
-  public static $modules = [];
+  protected static $modules = [];
 }

SystemSortByInfoNameRector

Fixes deprecated system_sort_modules_by_info_name() calls

-uasort($modules, 'system_sort_modules_by_info_name');
+uasort($modules, [ModuleExtensionList::class, 'sortByName']);

TaxonomyTermLoadMultipleByNameRector

Refactor function call to an entity storage method

-$terms = taxonomy_term_load_multiple_by_name(
-    'Foo',
-    'topics'
-);
+$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties([
+    'name' => 'Foo',
+    'vid' => 'topics',
+]);

TaxonomyVocabularyGetNamesDrupalStaticResetRector

Refactor drupal_static_reset('taxonomy_vocabulary_get_names') to entity storage reset cache

-drupal_static_reset('taxonomy_vocabulary_get_names');
+\Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->resetCache();

TaxonomyVocabularyGetNamesRector

Refactor function call to an entity storage method

-$vids = taxonomy_vocabulary_get_names();
+$vids = \Drupal::entityQuery('taxonomy_vocabulary')->execute();

UiHelperTraitDrupalPostFormRector

Fixes deprecated UiHelperTrait::drupalPostForm() calls

 $edit = [];
 $edit['action'] = 'action_goto_action';
-$this->drupalPostForm('admin/config/system/actions', $edit, 'Create');
+$this->drupalGet('admin/config/system/actions');
+$this->submitForm($edit, 'Create');
 $edit['action'] = 'action_goto_action_1';
-$this->drupalPostForm(null, $edit, 'Edit');
+$this->submitForm($edit, 'Edit');

UserPasswordRector

Fixes deprecated user_password() calls

-$pass = user_password();
-$shorter_pass = user_password(8);
+$pass = \Drupal::service('password_generator')->generate();
+$shorter_pass = \Drupal::service('password_generator')->generate(8);

DrupalRector

ClassConstantToClassConstantRector

Fixes deprecated class contant use, used in Drupal 9.1 deprecations

🔧 configure it!

-$value = Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_NAME;
-$value2 = Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT;
-$value3 = Symfony\Cmf\Component\Routing\RouteObjectInterface::CONTROLLER_NAME;
+$value = \Drupal\Core\Routing\RouteObjectInterface::ROUTE_NAME;
+$value2 = \Drupal\Core\Routing\RouteObjectInterface::ROUTE_OBJECT;
+$value3 = \Drupal\Core\Routing\RouteObjectInterface::CONTROLLER_NAME;

ConstantToClassConstantRector

Fixes deprecated contant use, used in Drupal 8 and 9 deprecations

🔧 configure it!

-$result = file_unmanaged_copy($source, $destination, DEPRECATED_CONSTANT);
+$result = file_unmanaged_copy($source, $destination, \Drupal\MyClass::CONSTANT);

DeprecationHelperRemoveRector

Remove DeprecationHelper calls for versions before configured minimum requirement

🔧 configure it!

 $settings = [];
 $filename = 'simple_filename.yaml';
-DeprecationHelper::backwardsCompatibleCall(\Drupal::VERSION, '9.1.0', fn() => new_function(), fn() => old_function());
-DeprecationHelper::backwardsCompatibleCall(\Drupal::VERSION, '10.5.0', fn() => SettingsEditor::rewrite($filename, $settings), fn() => drupal_rewrite_settings($settings, $filename));
+drupal_rewrite_settings($settings, $filename);
 DeprecationHelper::backwardsCompatibleCall(\Drupal::VERSION, '11.1.0', fn() => new_function(), fn() => old_function());

FunctionToServiceRector

Fixes deprecated function to service calls, used in Drupal 8 and 9 deprecations

🔧 configure it!

-$path = drupal_realpath($path);
+$path = \Drupal::service('file_system')
+    ->realpath($path);

-$result = drupal_render($elements);
+$result = \Drupal::service('renderer')->render($elements);

-$result = drupal_render_root($elements);
+$result = \Drupal::service('renderer')->renderRoot($elements);

-$display = entity_get_display($entity_type, $bundle, $view_mode)
+$display = \Drupal::service('entity_display.repository')
+    ->getViewDisplay($entity_type, $bundle, $view_mode);

-$display = entity_get_form_display($entity_type, $bundle, $form_mode)
+$display = \Drupal::service('entity_display.repository')
+    ->getFormDisplay($entity_type, $bundle, $form_mode);

-file_copy();
+\Drupal::service('file.repository')->copy();

-$dir = file_directory_temp();
+$dir = \Drupal::service('file_system')->getTempDirectory();

-file_move();
+\Drupal::service('file.repository')->move();

-$result = file_prepare_directory($directory, $options);
+$result = \Drupal::service('file_system')->prepareDirectory($directory, $options);

-file_save_data($data);
+\Drupal::service('file.repository')->writeData($data);

-$files = file_scan_directory($directory);
+$files = \Drupal::service('file_system')->scanDirectory($directory);

-$result = file_unmanaged_save_data($data, $destination, $replace);
+$result = \Drupal::service('file_system')->saveData($data, $destination, $replace);

-$result = file_uri_target($uri)
+$result = \Drupal::service('stream_wrapper_manager')->getTarget($uri);

-$date = format_date($timestamp, $type, $format, $timezone, $langcode);
+$date = \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);

-$date = format_date($timestamp, $type, $format, $timezone, $langcode);
+$date = \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);

-$output = render($build);
+$output = \Drupal::service('renderer')->render($build);

FunctionToStaticRector

Fixes deprecated file_directory_os_temp() calls, used in Drupal 8, 9 and 10 deprecations

🔧 configure it!

-$dir = file_directory_os_temp();
+$dir = \Drupal\Component\FileSystem\FileSystem::getOsTemporaryDirectory();

 $settings = [];
 $filename = 'simple_filename.yaml';
-drupal_rewrite_settings($settings, $filename);
+SettingsEditor::rewrite($filename, $settings);

 $settings = [];
 $filename = 'simple_filename.yaml';
-drupal_rewrite_settings($settings, $filename);
+SettingsEditor::rewrite($filename, $settings);

MethodToMethodWithCheckRector

Fixes deprecated MetadataBag::clearCsrfTokenSeed() calls, used in Drupal 8 and 9 deprecations

🔧 configure it!

 $metadata_bag = new \Drupal\Core\Session\MetadataBag(new \Drupal\Core\Site\Settings([]));
-$metadata_bag->clearCsrfTokenSeed();
+$metadata_bag->stampNew();

-$url = $entity->urlInfo();
+$url = $entity->toUrl();

 /* @var \Drupal\node\Entity\Node $node */
 $node = \Drupal::entityTypeManager()->getStorage('node')->load(123);
 $entity_type = $node->getEntityType();
-$entity_type->getLowercaseLabel();
+$entity_type->getSingularLabel();

ShouldCallParentMethodsRector

PHPUnit based tests should call parent methods (setUp, tearDown)

 namespace Drupal\Tests\Rector\Deprecation\PHPUnit\ShouldCallParentMethodsRector\fixture;

 use Drupal\KernelTests\KernelTestBase;

 final class SetupVoidTest extends KernelTestBase {

     protected function setUp(): void
     {
+        parent::setUp();
         $test = 'doing things';
     }

     protected function tearDown(): void
     {
+        parent::tearDown();
         $test = 'doing things';
     }

 }