You are here

class ShurlyEditForm in ShURLy 8

ShurlyActionsForm.

Hierarchy

Expanded class hierarchy of ShurlyEditForm

1 string reference to 'ShurlyEditForm'
shurly.routing.yml in ./shurly.routing.yml
shurly.routing.yml

File

src/Form/ShurlyEditForm.php, line 16

Namespace

Drupal\shurly\Form
View source
class ShurlyEditForm extends FormBase {

  /**
   * Access check for editing a short url.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   * @param $rid
   */
  public function access(AccountInterface $account, $rid) {
    if (is_numeric($rid)) {
      $row = \Drupal::database()
        ->query('SELECT uid, source, destination FROM {shurly} WHERE rid = :rid', [
        'rid' => $rid,
      ])
        ->fetchObject();

      // If there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access.
      return AccessResult::allowedIf($account
        ->hasPermission('administer short URLs') || $account
        ->hasPermission('edit own URLs') && $row->uid == $account
        ->id());
    }
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $rid = NULL) {
    $shurly_link = \Drupal::database()
      ->query('SELECT * FROM {shurly} WHERE rid = :rid', [
      'rid' => $rid,
    ])
      ->fetchAllAssoc('rid');
    $shurly_history = \Drupal::database()
      ->query('SELECT * FROM {shurly_history} WHERE rid = :rid', [
      'rid' => $rid,
    ])
      ->fetchAll();
    $shurly_history_count = count($shurly_history);

    // Store the current values.
    $form_state
      ->setStorage([
      'shurly' => [
        'rid' => $rid,
        'source' => $shurly_link[$rid]->source,
        'count' => $shurly_link[$rid]->count,
        'destination' => urldecode($shurly_link[$rid]->destination),
      ],
    ]);
    if ($shurly_history) {
      $form['history'] = [
        '#prefix' => '<table>',
        '#suffix' => '</table>',
        '#tree' => TRUE,
      ];
      $form['history']['header'] = [
        '#markup' => '<thead>
        <tr>
          <th>' . t('Source') . '</th>
          <th>' . t('Changed') . '</th>
        </tr>
      </thead>',
      ];
      for ($i = 0; $i < $shurly_history_count; $i++) {
        $form['history']['row_' . $i] = [
          '#prefix' => '<tr class="' . ($i % 2 ? "odd" : "even") . '">',
          '#suffix' => '</tr>',
        ];
        $form['history']['row_' . $i]['destination'] = [
          '#prefix' => '<td>',
          '#suffix' => '</td>',
          '#markup' => link::fromTextAndUrl(Unicode::truncate($shurly_history[$i]->destination, 30), Url::fromUri($shurly_history[$i]->destination, [
            'attributes' => [
              'target' => [
                '_blank',
              ],
            ],
          ]))
            ->toString(),
        ];
        $form['history']['row_' . $i]['last_date'] = [
          '#prefix' => '<td>',
          '#suffix' => '</td>',
          '#markup' => \Drupal::service('date.formatter')
            ->format($shurly_history[$i]->last_date, 'short'),
        ];
      }
    }
    $form['source'] = [
      '#type' => 'textfield',
      '#title' => 'source',
      '#value' => $shurly_link[$rid]->source,
      '#disabled' => TRUE,
    ];
    $form['destination'] = [
      '#type' => 'textfield',
      '#title' => 'destination',
      '#value' => $shurly_link[$rid]->destination,
    ];
    $form['rid'] = [
      '#type' => 'hidden',
      '#value' => $rid,
    ];
    $form['count'] = [
      '#type' => 'hidden',
      '#value' => $shurly_link[$rid]->count,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Submit',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!shurly_validate_long($form_state
      ->getValue('destination'))) {
      $form_state
        ->setErrorByName('long_url', t('Invalid URL'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $storage =& $form_state
      ->getStorage();
    $rid = $storage['shurly']['rid'];
    $new_destination = $form_state
      ->getValue('destination');
    $request_time = \Drupal::time()
      ->getRequestTime();

    // Get the most recent history for this redirect (if exists)
    $previous_history = \Drupal::database()
      ->query('SELECT * FROM {shurly_history} WHERE rid = :rid ORDER BY vid DESC LIMIT 1', [
      'rid' => $rid,
    ])
      ->fetchAssoc();

    // Still to add: vid, count
    // First save the current data into the history table for future reference.
    \Drupal::database()
      ->query('INSERT INTO {shurly_history} (rid, vid, source, destination, last_date, count) VALUES (:rid, :vid, :source, :destination, :last_date, :count)', [
      ':rid' => $rid,
      ':vid' => isset($previous_history['vid']) ? $previous_history['vid'] + 1 : 0,
      ':source' => $storage['shurly']['source'],
      ':destination' => $storage['shurly']['destination'],
      ':last_date' => $request_time,
      ':count' => $storage['shurly']['count'],
    ]);

    // Update access information on this row.
    \Drupal::database()
      ->query('UPDATE {shurly} SET destination = :new_destination, count = :reset_count WHERE rid = :rid', [
      ':new_destination' => $new_destination,
      ':reset_count' => 0,
      'rid' => $rid,
    ]);
    unset($storage['shurly']);
    $this
      ->messenger()
      ->addStatus(t('URL has been edited.'));
  }

}

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::$configFactory protected property The config factory. 1
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
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.
ShurlyEditForm::access public function Access check for editing a short url.
ShurlyEditForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ShurlyEditForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ShurlyEditForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ShurlyEditForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.