You are here

function shurly_shorten in ShURLy 8

Same name and namespace in other branches
  1. 6 shurly.module \shurly_shorten()
  2. 7 shurly.module \shurly_shorten()

API function to shorten a URL.

@arg $long_url - the long URL to shorten @arg $custom - optional custom short URL

Return value

an array with the following keys 'success' => TRUE or FALSE 'error' => reason for for failure 'long_url' => the long url 'short_url' => the short url

3 calls to shurly_shorten()
DefaultController::shurly_service_shorten in shurly_service/src/Controller/DefaultController.php
ShurlyFilter::process in src/Plugin/Filter/ShurlyFilter.php
Performs the filter processing.
shurly_service_shorten in shurly_service/shurly_service.inc
Callback for shurly/api/shorten.

File

./shurly.module, line 139
Description http://www.youtube.com/watch?v=Qo7qoonzTCE.

Code

function shurly_shorten($long_url, $custom = NULL, $account = NULL) {
  $success = FALSE;
  $account = $account ? $account : \Drupal::currentUser();
  $error = '';
  $no_save = FALSE;
  $rate_limit = shurly_rate_limit_allowed($account);
  if (!$rate_limit['allowed']) {
    $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', [
      '@rate' => $rate_limit['rate'],
      '@time' => $rate_limit['time'],
    ]);
  }
  elseif (!shurly_validate_long($long_url)) {
    $error = t('Invalid long URL.');
  }
  elseif (is_null($custom)) {
    $latest = shurly_get_latest_short($long_url, $account
      ->id());
    if ($latest) {
      $no_save = TRUE;
      $success = TRUE;
      $short = $latest;
    }
    else {
      $short = shurly_next_url();
    }
  }
  else {
    $short = $custom;
    if (!shurly_validate_custom($short) || !shurly_path_available($short)) {
      $error .= $error ? ' ' : '';
      $error .= t('Invalid short URL.');
    }
    elseif (shurly_url_exists($short)) {
      $error .= $error ? ' ' : '';
      $error .= t('Existing short URL.');
    }
  }
  if (!$error && !$no_save) {
    if (shurly_save_url($long_url, $short, $account, $custom)) {
      $success = TRUE;
    }
    else {
      $error = t('Unknown database error.');
    }
  }
  return [
    'success' => $success,
    'error' => $error,
    'longUrl' => $long_url,
    'shortUrl' => isset($short) ? _surl($short, [
      'absolute' => TRUE,
    ]) : '',
  ];
}