knowledge-8.x-1.x-dev/src/Plugin/Action/ChangeUserWave.php
src/Plugin/Action/ChangeUserWave.php
<?php
namespace Drupal\knowledge\Plugin\Action;
use Drupal\Core\Action\ConfigurableActionBase;
use Drupal\Core\Entity\DependencyTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Sets the wave to a user.
*
* @Action(
* id = "knowledge_set_user_wave_action",
* label = @Translation("Sets the wave of the selected users"),
* type = "user"
* )
*/
class ChangeUserWave extends ConfigurableActionBase implements ContainerFactoryPluginInterface {
use DependencyTrait;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition
);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'wave' => '0',
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['wave'] = [
'#type' => 'number',
'#title' => $this->t('Wave'),
'#default_value' => $this->configuration['wave'],
'#required' => TRUE,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['wave'] = $form_state->getValue('wave');
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$this->addDependency('config', 'field.storage.user.knowledge_wave');
return $this->dependencies;
}
/**
* {@inheritdoc}
*/
public function access($object, ?AccountInterface $account = NULL, $return_as_object = FALSE) {
/** @var \Drupal\user\UserInterface $object */
$access = $object->access('update', $account, TRUE)
->andIf($object->roles->access('edit', $account, TRUE));
return $return_as_object ? $access : $access->isAllowed();
}
/**
* {@inheritdoc}
*/
public function execute($account = NULL) {
$wave = $this->configuration['wave'];
// Skip adding the role to the user if they already have it.
if ($account !== FALSE && $account->get('knowledge_wave')->value != intval($wave)) {
// For efficiency manually save the original account before applying
// any changes.
$account->original = clone $account;
$account->knowledge_wave->value = $wave;
$account->save();
}
}
}
