Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UHF-9213: Run phpstan #162

Merged
merged 4 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,11 @@ jobs:

- name: Run PHPCS
working-directory: ${{ env.DRUPAL_ROOT }}
run: |
vendor/bin/phpcs $MODULE_FOLDER --standard=Drupal --extensions=php,module,inc,install,test,info
run: vendor/bin/phpcs $MODULE_FOLDER --standard=Drupal,DrupalPractice --extensions=php,module,inc,install,test,info

- name: Run phpstan
working-directory: ${{ env.DRUPAL_ROOT }}
run: vendor/bin/phpstan analyze -c $MODULE_FOLDER/phpstan.neon $MODULE_FOLDER

- name: Start services
working-directory: ${{ env.DRUPAL_ROOT }}
Expand Down
6 changes: 6 additions & 0 deletions helfi_tpr.module
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ declare(strict_types = 1);
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountInterface;

Expand Down Expand Up @@ -226,6 +227,7 @@ function template_preprocess_tpr_ontology_word_details(array &$variables) : void
* Implements hook_ENTITY_TYPE_access().
*/
function helfi_tpr_tpr_unit_access(EntityInterface $entity, $operation, AccountInterface $account) : AccessResult {
assert($entity instanceof EntityPublishedInterface);
// Allow user to view unpublished Units based on permission.
if ($operation === 'view' && !$entity->isPublished()) {
return AccessResult::allowedIfHasPermission($account, 'view unpublished tpr_unit');
Expand All @@ -238,6 +240,7 @@ function helfi_tpr_tpr_unit_access(EntityInterface $entity, $operation, AccountI
* Implements hook_ENTITY_TYPE_access().
*/
function helfi_tpr_tpr_service_access(EntityInterface $entity, $operation, AccountInterface $account) : AccessResult {
assert($entity instanceof EntityPublishedInterface);
// Allow user to view unpublished Services based on permission.
if ($operation === 'view' && !$entity->isPublished()) {
return AccessResult::allowedIfHasPermission($account, 'view unpublished tpr_service');
Expand All @@ -250,6 +253,7 @@ function helfi_tpr_tpr_service_access(EntityInterface $entity, $operation, Accou
* Implements hook_ENTITY_TYPE_access().
*/
function helfi_tpr_tpr_service_channel_access(EntityInterface $entity, $operation, AccountInterface $account) : AccessResult {
assert($entity instanceof EntityPublishedInterface);
// Allow user to view unpublished Service channels based on permission.
if ($operation === 'view' && !$entity->isPublished()) {
return AccessResult::allowedIfHasPermission($account, 'view unpublished tpr_service_channel');
Expand All @@ -262,6 +266,7 @@ function helfi_tpr_tpr_service_channel_access(EntityInterface $entity, $operatio
* Implements hook_ENTITY_TYPE_access().
*/
function helfi_tpr_tpr_errand_service_access(EntityInterface $entity, $operation, AccountInterface $account) : AccessResult {
assert($entity instanceof EntityPublishedInterface);
// Allow user to view unpublished Errand services based on permission.
if ($operation === 'view' && !$entity->isPublished()) {
return AccessResult::allowedIfHasPermission($account, 'view unpublished tpr_errand_service');
Expand All @@ -274,6 +279,7 @@ function helfi_tpr_tpr_errand_service_access(EntityInterface $entity, $operation
* Implements hook_query_TAG_alter().
*/
function helfi_tpr_query_owd_relationship_alter(AlterableInterface $query) : void {
/** @var \Drupal\Core\Entity\Query\QueryAggregateInterface $query */
$query->groupBy('id');
}

Expand Down
1 change: 1 addition & 0 deletions helfi_tpr.views_execution.inc
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use Drupal\views\ViewExecutable;
*/
function helfi_tpr_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'unit_search' || $view->id() == 'service_units') {
assert(isset($query->orderby));
// Use the CASE function from helfi_tpr_views_pre_execute() for sorting.
$query->orderby[0]['field'] = 'name_sort';
$query->orderby[0]['direction'] = 'ASC';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,12 @@ public function settingsForm(array $form, FormStateInterface $form_state): array

$elements['minimum_value'] = [
'#type' => 'number',
'#title' => t('Minimum value', [], ['context' => 'decimal places']),
'#title' => $this->t('Minimum value', [], ['context' => 'decimal places']),
'#step' => '.01',
'#min' => 0,
'#max' => 1000,
'#default_value' => $this->getSetting('minimum_value'),
'#description' => t('If the number is smaller than minimum value, minimum value is shown.'),
'#description' => $this->t('If the number is smaller than minimum value, minimum value is shown.'),
'#weight' => 7,
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
Expand Down Expand Up @@ -79,6 +80,7 @@ public static function sortByAddress(ViewExecutable $view): ViewExecutable {
$results = $view->result;
$distances = [];
foreach ($results as $result) {
assert($result->_entity instanceof ContentEntityInterface);
if (empty($result->_entity->get('latitude')) || empty($result->_entity->get('longitude'))) {
continue;
}
Expand All @@ -94,6 +96,7 @@ public static function sortByAddress(ViewExecutable $view): ViewExecutable {

// Sort results array by distances: nearest first.
uasort($results, function ($left, $right) use ($distances) {
assert($left->_entity instanceof ContentEntityInterface && $right->_entity instanceof ContentEntityInterface);
return match ($distances[$left->_entity->get('id')->getString()] >= $distances[$right->_entity->get('id')->getString()]) {
FALSE => (-1),
TRUE => 1,
Expand Down
27 changes: 27 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
parameters:
fileExtensions:
- php
- module
- install
paths:
- ./
excludePaths:
- vendor
level: 3
checkMissingIterableValueType: false
treatPhpDocTypesAsCertain: false
ignoreErrors:
-
message: '#^Access to an undefined property#'
paths:
- tests/src/Kernel/UnitMigrationTest.php
- tests/src/Kernel/ServiceMigrationTest.php
- tests/src/Kernel/ServiceChannelMigrationTest.php
- tests/src/Kernel/Plugin/Field/FieldType/ConnectionItemTest.php
- tests/src/Kernel/Plugin/Field/FieldType/AccessibilitySentenceItemTest.php
- tests/src/Functional/UnitListTest.php
- tests/src/Functional/ServiceListTest.php
-
message: '#^\\Drupal calls should be avoided in classes, use dependency injection instead#'
path: src/Entity/TranslationHandler.php
count: 1
6 changes: 4 additions & 2 deletions src/Entity/Form/ContentEntityForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,16 +126,18 @@ public function form(array $form, FormStateInterface $form_state) {
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
public function save(array $form, FormStateInterface $form_state) : int {
$entity_type = $this->entity->getEntityTypeId();

parent::save($form, $form_state);
$status = parent::save($form, $form_state);

$this->messenger()->addStatus($this->t('%title saved.', ['%title' => $this->entity->label()]));

$form_state->setRedirect('entity.' . $entity_type . '.canonical', [
$entity_type => $this->entity->id(),
]);

return $status;
}

}
6 changes: 3 additions & 3 deletions src/Entity/Listing/ListBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
/**
* Provides a list controller for the tpr entity types.
*/
class ListBuilder extends EntityListBuilder {
final class ListBuilder extends EntityListBuilder {

/**
* The date formatter service.
Expand Down Expand Up @@ -45,8 +45,8 @@ public function __construct(EntityTypeInterface $entity_type, EntityStorageInter
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) : self {
return new self(
$entity_type,
$container->get('entity_type.manager')->getStorage($entity_type->id()),
$container->get('date.formatter'),
Expand Down
2 changes: 1 addition & 1 deletion src/Entity/OntologyWordDetails.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public function getDetailByAnother(string $fieldName, string $detail, string $fi
}
}
}
return $data ?? NULL;
return $data;
tuutti marked this conversation as resolved.
Show resolved Hide resolved
}

}
2 changes: 1 addition & 1 deletion src/Entity/TprEntityBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ abstract class TprEntityBase extends RemoteEntityBase implements RevisionableInt
* These are fields that needs to be duplicated and
* be overridable by the end user.
*
* @var \Drupal\Core\Field\BaseFieldDefinition[]
* @var \Drupal\Core\Field\FieldDefinitionInterface[]
tuutti marked this conversation as resolved.
Show resolved Hide resolved
*/
protected static array $overrideFields = [];

Expand Down
2 changes: 1 addition & 1 deletion src/Entity/Unit.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ public function getPictureUrl() : ? string {
return $this->get('picture_url')->value;
}

/** @var \Drupal\file\FileInterface $file */
if ($file = $picture_url->get('field_media_image')->entity) {
/** @var \Drupal\file\FileInterface $file */
try {
return $file->createFileUrl(FALSE) ?: NULL;
}
Expand Down
39 changes: 30 additions & 9 deletions src/Plugin/Field/FieldFormatter/ErrandServicesChannelFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\helfi_tpr\Entity\ChannelType;
use Drupal\helfi_tpr\Entity\ChannelTypeCollection;
use Drupal\helfi_tpr\Entity\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Field formatter to render errand service maps.
Expand All @@ -23,7 +26,29 @@
* }
* )
*/
class ErrandServicesChannelFormatter extends FormatterBase {
final class ErrandServicesChannelFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

/**
* The renderer service.
*
* @var \Drupal\Core\Render\RendererInterface
*/
private RendererInterface $renderer;

/**
* {@inheritdoc}
*/
public static function create(
ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition
) : self {
$instance = parent::create($container, $configuration, $plugin_id,
$plugin_definition);
$instance->renderer = $container->get('renderer');
return $instance;
}

/**
* {@inheritdoc}
Expand All @@ -48,10 +73,9 @@ public function settingsSummary() : array {
}

return [
$this->t('Showing @list', [
(string) $this->t('Showing @list', [
'@list' => implode(', ', $selected_channels),
],
),
]),
];
}

Expand Down Expand Up @@ -132,18 +156,15 @@ public function viewElements(FieldItemListInterface $items, $langcode) : array {
}
$channelTypes = $this->getChannelTypes();

/** @var \Drupal\Core\Render\Renderer $renderer */
$renderer = \Drupal::service('renderer');

$channel_list = [];
/** @var \Drupal\helfi_tpr\Entity\ErrandService[] $errand_services */
$errand_services = $items->referencedEntities();
$item_list = [
'#theme' => 'item_list',
'#items' => [],
];

foreach ($errand_services as $errand_service) {
/** @var \Drupal\helfi_tpr\Entity\ErrandService $errand_service */
foreach ($errand_service->getChannels() as $channel) {
if (isset($channel_list[$channel->getType()])
|| empty($this->getSetting('sort_order')[$channel->getType()]['show'])) {
Expand All @@ -154,7 +175,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) : array {
'#name' => $this->getSetting('sort_order')[$channel->getType()]['label'],
'#weight' => $channelTypes[$channel->getType()]->weight,
];
$renderer->addCacheableDependency($item_list, $channel);
$this->renderer->addCacheableDependency($item_list, $channel);
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/Plugin/views/argument/ServiceIdArgument.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Drupal\helfi_tpr\Plugin\views\argument;

use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
use Drupal\views\Plugin\views\query\Sql;

/**
* Argument for service_id column.
Expand Down Expand Up @@ -30,6 +31,9 @@ public function query($group_by = FALSE) : void {
}

$group = $this->query->setWhereGroup('OR');

assert($this->query instanceof Sql);

if (!empty($ids)) {
$this->query->addWhere($group, 'id', $ids, 'IN');
}
Expand Down
8 changes: 4 additions & 4 deletions src/Plugin/views/filter/ProvidedLanguages.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class ProvidedLanguages extends InOperator {
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL): void {
parent::init($view, $display, $options);
$this->valueTitle = t('Allowed languages');
$this->valueTitle = (string) $this->t('Allowed languages');
$this->definition['options callback'] = [$this, 'generateOptions'];
}

Expand All @@ -34,9 +34,9 @@ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$o
*/
public function generateOptions(): array {
return [
'fi' => t('Finnish'),
'sv' => t('Swedish'),
'se' => t('North Sami'),
'fi' => (string) $this->t('Finnish'),
'sv' => (string) $this->t('Swedish'),
'se' => (string) $this->t('North Sami'),
];
}

Expand Down
2 changes: 2 additions & 0 deletions src/Plugin/views/filter/Status.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Drupal\helfi_tpr\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Drupal\views\Plugin\views\query\Sql;

/**
* Filter by published status.
Expand All @@ -28,6 +29,7 @@ public function canExpose() {
public function query() {
$table = $this->ensureMyTable();
$snippet = "$table.content_translation_status = 1 OR ***VIEW_UNPUBLISHED_TPR_ENTITIES*** = 1";
assert($this->query instanceof Sql);
$this->query->addWhereExpression($this->options['group'], $snippet);
}

Expand Down
2 changes: 2 additions & 0 deletions src/Plugin/views/relationship/TagOwdRelationship.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Drupal\helfi_tpr\Plugin\views\relationship;

use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\Plugin\views\relationship\RelationshipPluginBase;

/**
Expand All @@ -20,6 +21,7 @@ class TagOwdRelationship extends RelationshipPluginBase {
*/
public function query() {
parent::query();
assert($this->query instanceof Sql);
$this->query->addTag('owd_relationship');
}

Expand Down
4 changes: 2 additions & 2 deletions src/TprViewsData.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ public function getViewsData() {

// Add relationship between Unit and Ontology word details.
$data['tpr_unit']['tpr_ontology_word_details'] = [
'title' => t('Ontology word details field data'),
'title' => $this->t('Ontology word details field data'),
'relationship' => [
'base' => 'tpr_ontology_word_details_field_data',
'base field' => 'unit_id',
'table' => 'tpr_unit',
'real field' => 'id',
'id' => 'tag_owd_relationship',
'label' => t('Ontology word details field data'),
'label' => $this->t('Ontology word details field data'),
],
];

Expand Down
Loading