Skip to content

Instantly share code, notes, and snippets.

@marcaddeo
Created January 22, 2019 19:37
Show Gist options
  • Save marcaddeo/47bcbe8de9ff631d661ce6744ac9d22e to your computer and use it in GitHub Desktop.
Save marcaddeo/47bcbe8de9ff631d661ce6744ac9d22e to your computer and use it in GitHub Desktop.
diff --git a/src/ActionLink/ActionLinkTypeBase.php b/src/ActionLink/ActionLinkTypeBase.php
index a14e37e..bc2a154 100644
--- a/src/ActionLink/ActionLinkTypeBase.php
+++ b/src/ActionLink/ActionLinkTypeBase.php
@@ -11,6 +11,7 @@ use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
+use Drupal\Core\Session\SessionManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\flag\FlagInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
@@ -31,6 +32,13 @@ abstract class ActionLinkTypeBase extends PluginBase implements ActionLinkTypePl
*/
protected $currentUser;
+ /**
+ * The session manager.
+ *
+ * @var \Drupal\Core\Session\SessionManagerInterface $sessionManager
+ */
+ protected $sessionManager;
+
use StringTranslationTrait;
use RedirectDestinationTrait;
@@ -45,11 +53,14 @@ abstract class ActionLinkTypeBase extends PluginBase implements ActionLinkTypePl
* The plugin definition array.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
+ * @param \Drupal\Core\Session\SessionManagerInterface $session_manager
+ * The session manager.
*/
- public function __construct(array $configuration, $plugin_id, array $plugin_definition, AccountInterface $current_user) {
+ public function __construct(array $configuration, $plugin_id, array $plugin_definition, AccountInterface $current_user, SessionManagerInterface $session_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->configuration += $this->defaultConfiguration();
$this->currentUser = $current_user;
+ $this->sessionManager = $session_manager;
}
/**
@@ -60,7 +71,8 @@ abstract class ActionLinkTypeBase extends PluginBase implements ActionLinkTypePl
$configuration,
$plugin_id,
$plugin_definition,
- $container->get('current_user')
+ $container->get('current_user'),
+ $container->get('session_manager')
);
}
@@ -144,7 +156,14 @@ abstract class ActionLinkTypeBase extends PluginBase implements ActionLinkTypePl
* @return string
*/
protected function getAction(FlagInterface $flag, EntityInterface $entity) {
+ // If an anonymous user does not have a session, that user has not yet
+ // flagged anything, so the action is "flag".
+ if ($this->currentUser->isAnonymous() && !$this->sessionManager->isStarted()) {
+ return 'flag';
+ }
+
return $flag->isFlagged($entity) ? 'unflag' : 'flag';
+
}
/**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment