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

Checks if the node have translation and if matches with the current l… #136

Merged
merged 2 commits into from
Apr 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
42 changes: 39 additions & 3 deletions src/Plugin/rest/resource/AlertsRestResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\openy_node_alert\Service\AlertManager;
use Drupal\path_alias\AliasManagerInterface;
use Drupal\Core\Path\CurrentPathStack;
Expand Down Expand Up @@ -93,6 +94,13 @@ class AlertsRestResource extends ResourceBase {
*/
protected $alertManager;

/**
* Language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;

/**
* Constructs a new AlertsRestResource object.
*
Expand Down Expand Up @@ -124,6 +132,8 @@ class AlertsRestResource extends ResourceBase {
* The router doing the actual routing.
* @param AlertManager $alert_manager
* The alert manager.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager service.
*/
public function __construct(
array $configuration,
Expand All @@ -139,7 +149,8 @@ public function __construct(
ModuleHandlerInterface $module_handler,
Request $request,
RequestMatcherInterface $router,
AlertManager $alert_manager
AlertManager $alert_manager,
LanguageManagerInterface $language_manager
) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

Expand All @@ -152,6 +163,7 @@ public function __construct(
$this->request = $request;
$this->router = $router;
$this->alertManager = $alert_manager;
$this->languageManager = $language_manager;
}

/**
Expand All @@ -172,7 +184,8 @@ public static function create(ContainerInterface $container, array $configuratio
$container->get('module_handler'),
$container->get('request_stack')->getCurrentRequest(),
$container->get('router.no_access_checks'),
$container->get('openy_node_alert.alert_manager')
$container->get('openy_node_alert.alert_manager'),
$container->get('language_manager')
);
}

Expand All @@ -195,11 +208,34 @@ public function get() {
}

$uri = $this->request->query->get('uri');

// Extract the language code from the URI.
$langcode = substr($uri, 1, 2);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andrebonon is there a more bulletproof way to get the language? Do we know the url will always always look the same?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's delve into the underlying issue here. The initial request constructs the entire page based on the detected language, which, in this case, is determined through the URL path. However, the subsequent request to /alert does not include the language in the path, leading Drupal to default to the primary language instead of maintaining the language from the original request.

My attempts to override the language for the /alert request were unsuccessful.
Therefore, I opted to redirect the /alert request to /{lang}/alert, enabling Drupal to correctly identify the appropriate translation for the request.

It's important to note that this solution specifically impacts the Language detection URL when utilizing the path option. It doesn't affect the domain option, session, or any other existing detection modes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the way to get the language, the other way I can think of would be using explode().
$path = explode('/', trim($uri, '/')); and get the $path[0].
That would help in cases we have custom lang codes or codes with 1 or 3 characters (what I guess don't follow ISO for lang codes).

Do you have any other suggestions?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andrebonon thanks for the detailed explanation. That all makes sense, and based on the situation I think your solution here makes sense. I understand that we have to rely on the URL for the language code, so let's move forward with your original solution.

$language = $this->languageManager->getLanguage($langcode);
$alert_language = NULL;
if ($language) {
$alert_language = $language->getId();
}

// Check if the first segment is a valid language code.
$request_langcode = substr($this->request->getPathInfo(), 1, 2);
$request_language = $this->languageManager->getLanguage($request_langcode);

if ($language && !$request_language || $request_language && $request_language->getId() != $alert_language) {
// Redirect to the same request URL with the language code added after the basePath.
$redirectUrl = $this->request->getSchemeAndHttpHost() . '/' . $langcode . $this->request->getRequestUri();
// Sets the HTTP Status code to 303 - See Other.
$response = new ModifiedResourceResponse(NULL, 303);
$response->headers->set('Location', $redirectUrl);
return $response;
}

$result = $this->router->match($uri);
if (!isset($result['node'])) {
return new ModifiedResourceResponse('Node not found');
}
[$sendAlerts, $alerts] = $this->alertManager->getAlerts($result['node']);

[$sendAlerts, $alerts] = $this->alertManager->getAlerts($result['node'], $alert_language);

$this->moduleHandler->alter('openy_node_alert_get', $sendAlerts, $alerts);

Expand Down
13 changes: 11 additions & 2 deletions src/Service/AlertManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function __construct(
EntityTypeManagerInterface $entity_type_manager,
AccountProxyInterface $current_user,
AliasManagerInterface $alias_manager,
PathMatcherInterface $path_matcher
PathMatcherInterface $path_matcher,
) {
$this->nodeStorage = $entity_type_manager->getStorage('node');
$this->currentUser = $current_user;
Expand Down Expand Up @@ -155,7 +155,7 @@ public function getServiceAlerts(EntityInterface $node) {
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \HttpException
*/
public function getAlerts(EntityInterface $node) {
public function getAlerts(EntityInterface $node, string|null $language = NULL) {
// Get data from draggableviews_structure table.
$query = $this->connection->select('draggableviews_structure', 'dvs');
$query->fields('dvs', ['view_name', 'view_display', 'entity_id', 'weight']);
Expand Down Expand Up @@ -192,6 +192,15 @@ public function getAlerts(EntityInterface $node) {
if (!empty($service_alert_ids) && !in_array($alert->id(), $service_alert_ids)) {
continue;
}

// Load the translation content.
if ($language) {
$available_translations = array_keys($alert->getTranslationLanguages());
if (in_array($language, $available_translations)) {
$alert = $alert->getTranslation($language);
}
}

if (!$alert->hasField('field_alert_visibility_pages')) {
if ($alert->hasField('field_alert_belongs') && !$alert->field_alert_belongs->isEmpty() && !$alert->field_alert_place->isEmpty()) {
$refid = $alert->field_alert_belongs->target_id;
Expand Down