- Issue created by @mradcliffe
Follow-up from π Add gitlab ci integration for code standards and eventual tests Active .
There are several phpstan code quality issues that can be resolved. The biggest one is to not use static methods on the Drupal
object.
FormBase already implements ContainerInjectionInterface, which allows us to use the static `create method`. It also has some helpful traits and includes requestStack
and configFactory
as protected members (although not injected).
Pre-existing methods:
// $config = \Drupal::config('node_swapper.settings')
$config = $this->configFactory->get('node_swapper.settings');
// $unpublish = \Drupal::request()->query->get('unpublish', $config->get('old_node_unpublish');
$unpublish = $this->getRequest()->query->get('unpublish', $config->get('old_node_unpublish');
Injecting dependencies:
public static function create(ContainerInterface $container) {
return new static(
// Replaces \Drupal::database().
$container->get('database'),
// Replaces \Drupal::time().
$container->get('datetime.time'),
// The static EntityInterface::load calls can be replaced as well.
$container->get('entity_type.manager'),
// Replaces \Drupal::service('path_alias.manager').
$container->get('path_alias.manager'),
);
}
// Example using PHP 8 code.
public function __construct(protected $database, protected $time, protected $entityTypeManager, protected $pathAliasManager) { }
Additionally we can be even cleaner, if we inject the dependencies for requestStack, configFactory, and messenger, using the setter methods
Remove use of \Drupal in forms by implementing the static create
method and the __construct
initialization method assigning the services to protected variables either via existing FormBase methods or via manual assignment.
This would make it easier to mock those dependencies in a Kernel test or pure unit test later.
No.
The classes are final so it doesn't matter.
No.
Active
1.1
Code