Skip to content

Commit

Permalink
Merge pull request #359 from City-of-Helsinki/UHF-9213
Browse files Browse the repository at this point in the history
UHF-9213: Run phpstan
  • Loading branch information
tuutti authored Nov 28, 2023
2 parents 7cc8fd9 + 67e5f02 commit 103c970
Show file tree
Hide file tree
Showing 15 changed files with 157 additions and 61 deletions.
7 changes: 5 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,11 @@ jobs:

- name: Run PHPCS
run: |
vendor/bin/phpcs public/modules/custom/ --ignore="*.js,*.css" --extensions=php,module,install --standard=Drupal
vendor/bin/phpcs public/themes/custom/ --ignore="*.js,*.css" --extensions=php,theme --standard=Drupal
vendor/bin/phpcs public/modules/custom/ --ignore="*.js,*.css" --extensions=php,module,install --standard=Drupal,DrupalPractice
vendor/bin/phpcs public/themes/custom/ --ignore="*.js,*.css" --extensions=php,theme --standard=Drupal,DrupalPractice
- name: Run phpstan
run: vendor/bin/phpstan analyze

- name: Download latest dump
env:
Expand Down
15 changes: 12 additions & 3 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
parameters:
treatPhpDocTypesAsCertain: false
fileExtensions:
- php
- module
- install
- theme
paths:
- ./public/modules/custom
- ./public/themes/custom
excludePaths:
- *Test.php
- *TestBase.php
- vendor
level: 3
checkMissingIterableValueType: false
treatPhpDocTypesAsCertain: false
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ function helfi_rekry_content_update_9003() {
];

foreach ($employmentTypeItems as $item) {
$term = Term::create([
Term::create([
'parent' => [],
'name' => $item['en'],
'vid' => 'employment_type',
Expand Down Expand Up @@ -100,7 +100,7 @@ function helfi_rekry_content_update_9003() {
];

foreach ($employmentItems as $item) {
$term = Term::create([
Term::create([
'parent' => [],
'name' => $item['en'],
'vid' => 'employment',
Expand Down Expand Up @@ -193,7 +193,7 @@ function helfi_rekry_content_update_9005() {
];

foreach ($employmentItems as $item) {
$term = Term::create([
Term::create([
'parent' => [],
'name' => $item['en'],
'vid' => 'employment',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
declare(strict_types = 1);

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityFormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\helfi_platform_config\DTO\ParagraphTypeCollection;
Expand All @@ -33,7 +34,9 @@ function helfi_rekry_content_entity_bundle_info_alter(array &$bundles): void {
* Implements hook_form_FORM_ID_alter().
*/
function helfi_rekry_content_form_node_job_listing_edit_form_alter(array &$form, FormStateInterface $form_state, string $form_id): void {
$user_edit_access = $form_state->getFormObject()
$formObject = $form_state->getFormObject();
assert($formObject instanceof EntityFormInterface);
$user_edit_access = $formObject
->getEntity()
->access('edit', \Drupal::currentUser());

Expand Down Expand Up @@ -164,7 +167,7 @@ function _helfi_rekry_content_get_video_url(string|NULL $url = NULL): ?string {
try {
// Use the same validation used in field validation.
$resource_url = $resolver->getResourceUrl($url);
$resource = \Drupal::service('media.oembed.resource_fetcher')
\Drupal::service('media.oembed.resource_fetcher')
->fetchResource($resource_url);
return $url;
}
Expand Down Expand Up @@ -435,7 +438,7 @@ function helfi_rekry_content_preprocess_block(&$variables) {

if (
empty($paragraph) ||
!in_array($entity->getType(), ['landing_page', 'page']) ||
!in_array($entity->bundle(), ['landing_page', 'page']) ||
!$paragraph instanceof ParagraphInterface
) {
return;
Expand Down Expand Up @@ -468,14 +471,14 @@ function helfi_rekry_content_views_query_alter(ViewExecutable $view, QueryPlugin
return;
}

/** @var \Drupal\taxonomy\Entity\Term $term */
$terms = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties(['field_external_id' => $task_area_external_id]);
if (!$terms) {
return;
}

/** @var \Drupal\taxonomy\Entity\Term $term */
$term = reset($terms);
$query->where[0]["conditions"][0]["value"][":node__field_task_area_field_task_area_target_id"] = $term->id();
}
Expand All @@ -502,12 +505,14 @@ function helfi_rekry_content_page_attachments(array &$attachments) : void {
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = Drupal::service('date.formatter');

// @phpstan-ignore-next-line
$publication_starts_datetime = $job_listing->get('field_publication_starts')->date->getTimestamp();
$publication_starts_formatted = $date_formatter->format($publication_starts_datetime, 'html_date');

/** @var Drupal\Core\Extension\ThemeHandler $theme_handler */
$theme_handler = Drupal::service('theme_handler');

$logo_image_url = '';
// Get the default share image as structured data logo.
if ($theme_handler->themeExists('hdbt')) {
$theme = $theme_handler->getTheme('hdbt');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
services:
Drupal\helfi_rekry_content\EventSubscriber\ImageImportSubscriber:
arguments: ['@file_system', '@config.factory']
arguments: ['@file_system', '@config.factory', '@current_user']
tags:
- { name: 'event_subscriber' }
Drupal\helfi_rekry_content\Plugin\Deriver:
Expand All @@ -10,7 +10,7 @@ services:
- { name: 'event_subscriber' }
helfi_rekry_content.job_listing_hide_missing:
class: Drupal\helfi_rekry_content\EventSubscriber\JobListingHideMissingSubscriber
arguments: ['@entity_type.manager', '@logger.channel.helfi_rekry_content']
arguments: ['@entity_type.manager', '@logger.channel.helfi_rekry_content', '@queue']
tags:
- { name: 'event_subscriber' }
helfi_rekry_content.job_listing_redirect_subscriber:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public function getOrganizationName() : string {
$storage = $this->entityTypeManager()
->getStorage('taxonomy_term');

// @phpstan-ignore-next-line
$organization_entity = $storage->load($this->get('field_organization_override')->first()->target_id);

if (!$organization_entity->hasTranslation($this->get('langcode')->value)) {
Expand Down Expand Up @@ -65,6 +66,7 @@ public function getEmploymentType() : string {
$storage = $this->entityTypeManager()
->getStorage('taxonomy_term');

// @phpstan-ignore-next-line
$employment_type_entity = $storage->load($this->get('field_employment_type')->first()->target_id);

if (!$employment_type_entity->hasTranslation($this->get('langcode')->value)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\File\FileSystem;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\media\Entity\Media;
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateImportEvent;
Expand All @@ -22,10 +23,16 @@ class ImageImportSubscriber implements EventSubscriberInterface {
*
* @param \Drupal\Core\File\FileSystem $fileSystem
* The file system service.
* @param Drupal\Core\Config\ConfigFactory $config
* @param \Drupal\Core\Config\ConfigFactory $config
* The settings service.
* @param \Drupal\Core\Session\AccountProxyInterface $currentUser
* The current user.
*/
public function __construct(private FileSystem $fileSystem, private ConfigFactory $config) {
public function __construct(
private FileSystem $fileSystem,
private ConfigFactory $config,
private AccountProxyInterface $currentUser
) {
}

/**
Expand All @@ -52,7 +59,8 @@ public function postRowSave(MigratePostRowSaveEvent $event): void {

$row = $event->getRow();
$title = $row->getSourceProperty('title');
$fileId = reset($event->getDestinationIdValues());
$destinationIdValues = $event->getDestinationIdValues();
$fileId = reset($destinationIdValues);

if ($mid = _helfi_rekry_content_get_media_image($fileId)) {
$media = Media::load($mid);
Expand All @@ -61,13 +69,13 @@ public function postRowSave(MigratePostRowSaveEvent $event): void {
'target_id' => $fileId,
'alt' => $title,
])
->setPublished(TRUE)
->setPublished()
->save();
}
else {
$media = Media::create([
'bundle' => 'job_listing_image',
'uid' => \Drupal::currentUser()->id(),
'uid' => $this->currentUser->id(),
'name' => $title,
'field_media_image' => [
'target_id' => $fileId,
Expand All @@ -76,7 +84,7 @@ public function postRowSave(MigratePostRowSaveEvent $event): void {
]);

$media->setName(basename($row->getDestinationProperty('destination_filename')))
->setPublished(TRUE)
->setPublished()
->save();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Drupal\helfi_rekry_content\EventSubscriber;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Queue\QueueFactory;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drush\Drupal\Migrate\MigrateMissingSourceRowsEvent;
use Psr\Log\LoggerInterface;
Expand All @@ -23,10 +24,13 @@ class JobListingHideMissingSubscriber implements EventSubscriberInterface {
* The entity type manager.
* @param \Psr\Log\LoggerInterface $logger
* Logger channel.
* @param \Drupal\Core\Queue\QueueFactory $queueFactory
* The queue factory.
*/
public function __construct(
protected EntityTypeManagerInterface $entityTypeManager,
protected LoggerInterface $logger,
protected QueueFactory $queueFactory,
) {}

/**
Expand Down Expand Up @@ -78,7 +82,8 @@ function ($values, $destinationValue) {
}

// Query missing nodes that are still published.
$query = \Drupal::entityQuery('node')
$query = $this->entityTypeManager->getStorage('node')
->getQuery()
->accessCheck(FALSE)
->condition('nid', $destinationIds, 'IN')
->condition('status', 1)
Expand All @@ -87,7 +92,7 @@ function ($values, $destinationValue) {

foreach ($nids as $nid) {
$job = ['nid' => $nid];
\Drupal::queue('job_listing_unpublish_worker')->createItem($job);
$this->queueFactory->get('job_listing_unpublish_worker')->createItem($job);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static function getSubscribedEvents() {
/**
* Method to prepare index.
*
* @param Drupal\elasticsearch_connector\Event\PrepareIndexEvent $event
* @param \Drupal\elasticsearch_connector\Event\PrepareIndexEvent $event
* The PrepareIndex event.
*/
public function prepareIndices(PrepareIndexEvent $event) {
Expand All @@ -33,6 +33,7 @@ public function prepareIndices(PrepareIndexEvent $event) {
'job_listings',
];
if (in_array($indexName, $finnishIndices)) {
/** @var array $indexConfig */
$indexConfig = $event->getIndexConfig();
$indexConfig['body']['settings']['analysis']['analyzer']['default']['type'] = 'finnish';
$event->setIndexConfig($indexConfig);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ public function __construct(ConfigFactoryInterface $config_factory, AliasManager
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
public static function create(ContainerInterface $container) : self {
return new self(
$container->get('config.factory'),
$container->get('path_alias.manager'),
);
Expand All @@ -74,6 +74,7 @@ protected function getEditableConfigNames() : array {
public function buildForm(array $form, FormStateInterface $form_state): array {
$siteConfig = $this->config('helfi_rekry_content.job_listings');

// phpcs:ignore
$searchPage = Node::load($siteConfig->get('search_page'));
$form['job_listings']['search_page'] = [
'#type' => 'entity_autocomplete',
Expand All @@ -86,6 +87,7 @@ public function buildForm(array $form, FormStateInterface $form_state): array {
'#description' => $this->t('Displayed after the related jobs block, for example.'),
];

// phpcs:ignore
$redirectPage = Node::load($siteConfig->get('redirect_403_page'));
$form['job_listings']['redirect_403_page'] = [
'#type' => 'entity_autocomplete',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\helfi_platform_config\EntityVersionMatcher;
use Drupal\node\Entity\Node;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Provides a 'OrganizationInformation' block.
Expand All @@ -15,13 +18,55 @@
* admin_label = @Translation("Organization information block"),
* )
*/
class OrganizationInformation extends BlockBase {
class OrganizationInformation extends BlockBase implements ContainerFactoryPluginInterface {

/**
* Constructs a new instance.
*
* @param array $configuration
* The configuration.
* @param string $plugin_id
* The plugin id.
* @param array $plugin_definition
* The plugin definition.
* @param \Drupal\helfi_platform_config\EntityVersionMatcher $entityVersionMatcher
* The entity version matcher.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The entity type manager.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private readonly EntityVersionMatcher $entityVersionMatcher,
private readonly EntityTypeManagerInterface $entityTypeManager,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}

/**
* {@inheritdoc}
*/
public static function create(
ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition
) : self {
return new self(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('helfi_platform_config.entity_version_matcher'),
$container->get('entity_type.manager'),
);
}

/**
* {@inheritdoc}
*/
public function getCacheTags() {
$matcher = \Drupal::service('helfi_platform_config.entity_version_matcher')->getType();
$matcher = $this->entityVersionMatcher->getType();

if (
!$matcher['entity'] ||
Expand All @@ -46,7 +91,7 @@ public function build() {
$build = [];

// Get current entity and entity version.
$entity_matcher = \Drupal::service('helfi_platform_config.entity_version_matcher')->getType();
$entity_matcher = $this->entityVersionMatcher->getType();

/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_matcher['entity'];
Expand All @@ -57,7 +102,7 @@ public function build() {
$entity->hasField('field_organization') &&
$entity->hasField('field_organization_description')
) {
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$view_builder = $this->entityTypeManager->getViewBuilder('node');
$build['organization_information'] = $view_builder->view($entity);
$build['organization_information']['#theme'] = 'organization_information_block';
}
Expand Down
Loading

0 comments on commit 103c970

Please sign in to comment.