You are here

class NodeAuthlinkNodeForm in Node authorize link 8

Class NodeAuthlinkNodeForm.

Hierarchy

Expanded class hierarchy of NodeAuthlinkNodeForm

1 string reference to 'NodeAuthlinkNodeForm'
node_authlink.routing.yml in ./node_authlink.routing.yml
node_authlink.routing.yml

File

src/Form/NodeAuthlinkNodeForm.php, line 18

Namespace

Drupal\node_authlink\Form
View source
class NodeAuthlinkNodeForm extends FormBase {

  /**
   * Drupal\Core\Config\ConfigFactoryInterface definition.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new NodeAuthlinkNodeForm object.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) {
    $this->configFactory = $config_factory;
    $this->entityTypeManager = $entity_type_manager;
  }
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'node_authlink_node_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $node = NULL) {
    if (!is_numeric($node)) {
      throw new NotFoundHttpException();
    }
    $config = $this->configFactory
      ->get('node_authlink.settings');
    $config_grants = $config
      ->get('grants');
    $node = Node::load($node);
    $form['disclaimer'] = [
      '#type' => 'markup',
      '#markup' => '<p>' . $this
        ->t('Use the following form to manage anonymous authlinks for performing View, Update or Delete tasks without any further authentication. The links available will depends on the configuration of this content type.') . '</p>',
    ];
    if (isset($config_grants[$node
      ->bundle()])) {
      foreach ($config_grants[$node
        ->bundle()] as $op) {
        if (!$op) {
          continue;
        }

        // If $op is view, load all revisions.
        $has_revisions = FALSE;
        if ($op == 'view') {
          $has_revisions = TRUE;
          $node_storage = $this->entityTypeManager
            ->getStorage('node');
          $result = $node_storage
            ->getQuery()
            ->allRevisions()
            ->condition($node
            ->getEntityType()
            ->getKey('id'), $node
            ->id())
            ->sort($node
            ->getEntityType()
            ->getKey('revision'), 'DESC')
            ->range(0, 50)
            ->execute();
          if (!empty($result)) {
            $revision_options = [];
            foreach ($result as $vid => $nid) {
              $revision = $node_storage
                ->loadRevision($vid);
              $langcode = $node
                ->language()
                ->getId();

              // Only show revisions that are affected by the language that is being
              // displayed.
              if ($revision
                ->hasTranslation($langcode) && $revision
                ->getTranslation($langcode)
                ->isRevisionTranslationAffected()) {

                // Use revision link to link to revisions that are not active.
                $dateFormatter = \Drupal::service('date.formatter');
                $date = $dateFormatter
                  ->format($revision->revision_timestamp->value, 'short');
                if ($revision
                  ->isDefaultRevision()) {
                  $revision_options[$vid] = [
                    'text' => $this
                      ->t('Current revision'),
                    'url' => node_authlink_get_url($node, $op),
                  ];
                }
                else {
                  $revision_options[$vid] = [
                    'text' => $date,
                    'url' => node_authlink_get_url($node, $op, $vid),
                  ];
                }
              }
            }
          }
        }
        if ($has_revisions) {
          $form['revisions'] = [
            '#type' => 'select',
            '#title' => $this
              ->t('Revisions'),
            '#options' => [],
          ];

          // @todo: use a table instead.
          foreach ($revision_options as $vid => $revision_option) {
            $form['revisions']['#options'][$vid] = $revision_option['text'];
            $form['link_' . $op . '_' . $vid] = [
              '#type' => 'item',
              '#markup' => "<p><strong>" . $op . "</strong>: " . $revision_option['url'] . "</p>",
              '#states' => [
                'visible' => [
                  '[name="revisions"]' => [
                    'value' => $vid,
                  ],
                ],
              ],
            ];
          }
        }
        else {
          $url = node_authlink_get_url($node, $op);
          if ($url) {

            // @todo: use a table instead.
            $form['link_' . $op] = [
              '#type' => 'item',
              '#markup' => "<p><strong>{$op}</strong>: {$url}</p>",
            ];
          }
        }
      }
      if (node_authlink_load_authkey($node
        ->id())) {
        $form['delete'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Delete authlink'),
          '#weight' => 10,
          '#submit' => [
            '::deleteAuthlink',
          ],
        ];
      }
      else {
        $form['create'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Create authlink'),
          '#weight' => 10,
          '#submit' => [
            '::createAuthlink',
          ],
        ];
      }
    }
    return $form;
  }

  /**
   * Create authlink submit callback.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function createAuthlink(array &$form, FormStateInterface $form_state) {
    node_authlink_create($form_state
      ->getBuildInfo()['args'][0]);
  }

  /**
   * Delete authlink submit callback.
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function deleteAuthlink(array &$form, FormStateInterface $form_state) {
    node_authlink_delete($form_state
      ->getBuildInfo()['args'][0]);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Display result.
    foreach ($form_state
      ->getValues() as $key => $value) {
      $this
        ->messenger()
        ->addMessage($key . ': ' . $value);
    }
  }

  /**
   * Checks that node_authlink was enabled for this content type.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   * @param $node
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   */
  public function access(AccountInterface $account, $node) {
    if (is_numeric($node)) {
      $node = Node::load($node);
      $enable = $this
        ->config('node_authlink.settings')
        ->get('enable');
      if (isset($enable[$node
        ->bundle()]) && $enable[$node
        ->bundle()] && ($account
        ->hasPermission('create and delete node authlinks') || $account
        ->hasPermission(sprintf('create and delete node %s authlinks', $node
        ->bundle())))) {
        return AccessResult::allowed();
      }
    }
    return AccessResult::forbidden();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
NodeAuthlinkNodeForm::$configFactory protected property Drupal\Core\Config\ConfigFactoryInterface definition. Overrides FormBase::$configFactory
NodeAuthlinkNodeForm::$entityTypeManager protected property The entity type manager.
NodeAuthlinkNodeForm::access public function Checks that node_authlink was enabled for this content type.
NodeAuthlinkNodeForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
NodeAuthlinkNodeForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
NodeAuthlinkNodeForm::createAuthlink public function Create authlink submit callback.
NodeAuthlinkNodeForm::deleteAuthlink public function Delete authlink submit callback.
NodeAuthlinkNodeForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
NodeAuthlinkNodeForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
NodeAuthlinkNodeForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
NodeAuthlinkNodeForm::__construct public function Constructs a new NodeAuthlinkNodeForm object.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.