billwerk_subscriptions-1.x-dev/src/Plugin/Action/BillwerkUserContractIdsClearAction.php
src/Plugin/Action/BillwerkUserContractIdsClearAction.php
<?php
declare(strict_types=1);
namespace Drupal\billwerk_subscriptions\Plugin\Action;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\billwerk_subscriptions\Subscriber;
use Drupal\user\UserInterface;
/**
* Provides an action to clear users Billwerk Contract ID account field.
*
* @Action(
* id = "billwerk_user_contract_ids_clear_action",
* label = @Translation("Clear users Billwerk Contract ID account field"),
* type = "user",
* category = @Translation("Billwerk Subscriptions"),
* )
*
* @DCG
* For updating entity fields consider extending FieldUpdateActionBase.
* @see \Drupal\Core\Field\FieldUpdateActionBase
*
* @DCG
* In order to set up the action through admin interface the plugin has to be
* configurable.
* @see https://www.drupal.org/project/drupal/issues/2815301
* @see https://www.drupal.org/project/drupal/issues/2815297
*
* @DCG
* The whole action API is subject of change.
* @see https://www.drupal.org/project/drupal/issues/2011038
*/
final class BillwerkUserContractIdsClearAction extends ActionBase {
/**
* {@inheritdoc}
*/
public function access($entity, ?AccountInterface $account = NULL, $return_as_object = FALSE): AccessResultInterface|bool {
/** @var \Drupal\user\UserInterface $entity */
$access = $entity->access('update', $account, TRUE)
->andIf(AccessResult::allowedIfHasPermission($account, 'billwerk_subscriptions_fetch_assign_contract_ids'));
return $return_as_object ? $access : $access->isAllowed();
}
/**
* {@inheritdoc}
*/
public function execute(?UserInterface $user = NULL): void {
if ($user !== NULL) {
// Clear the billwerk contract ID field:
$user->set(Subscriber::USER_FIELD_BILLWERK_CONTRACT_ID, '');
$user->save();
}
}
}
