diff --git a/config/install/views.view.shurly_admin.yml b/config/install/views.view.shurly_admin.yml
index 8f1332f..0384b26 100755
--- a/config/install/views.view.shurly_admin.yml
+++ b/config/install/views.view.shurly_admin.yml
@@ -721,7 +721,7 @@ display:
         title: 'Short URLs'
         description: ''
         expanded: false
-        parent: system.admin
+        parent: shurly.admin
         weight: 0
         context: '0'
         menu_name: admin
diff --git a/config/schema/shurly.schema.yml b/config/schema/shurly.schema.yml
index f945881..6e47907 100755
--- a/config/schema/shurly.schema.yml
+++ b/config/schema/shurly.schema.yml
@@ -3,9 +3,9 @@ shurly.settings:
   label: Settings
   mapping:
     shurly_base:
-     type: string
+      type: string
     shurly_redirect_page:
-      type: boolean
+      type: string
     shurly_forbid_localhost:
       type: boolean
     shurly_forbid_private_ips:
diff --git a/js/shurly.js b/js/shurly.js
index e655084..07ddf57 100755
--- a/js/shurly.js
+++ b/js/shurly.js
@@ -6,7 +6,7 @@
 (function ($) {
   Drupal.behaviors.ShurlyClipboardjs = {
     attach: function (context, settings) {
-       if ($('#edit-result').length) {
+      if ($('#edit-result').length) {
 
         // Initialize clipboard.js.
         Drupal.clipboard = new Clipboard('#edit-result');
@@ -31,7 +31,7 @@
 
             // Show tooltip.
             $target.tooltip({
-              position: { my: "center", at: "center" }
+              position: {my: "center", at: "center"}
             }).mouseover();
 
             // Destroy tooltip after delay.
diff --git a/shurly.css b/shurly.css
index 5bee98d..1ce7497 100755
--- a/shurly.css
+++ b/shurly.css
@@ -14,24 +14,24 @@
 }
 
 #shurly-copy-container {
-  display:inline;
+  display: inline;
 }
 
 #shurly-copy {
   border: 2px outset #999;
-  background-color: #CCC;
+  background-color: #ccc;
   display: inline;
   padding: .1em .3em;
 }
 
 #shurly-copy.hover {
   border-color: #777;
-  background-color: #DDD;
+  background-color: #ddd;
 }
 
 .shurly-bookmarklet {
   background-color: #999;
-  color: #FFF;
+  color: #fff;
   padding: .1em .5em;
   text-decoration: none;
   -moz-border-radius: .7em;
@@ -39,7 +39,7 @@
 }
 
 .shurly-bookmarklet:hover {
-  background-color: #CCC;
+  background-color: #ccc;
   text-decoration: none;
   color: #000;
 }
\ No newline at end of file
diff --git a/shurly.install b/shurly.install
index 74ea94b..029cd08 100755
--- a/shurly.install
+++ b/shurly.install
@@ -9,177 +9,171 @@
  * Implements hook_schema().
  */
 function shurly_schema() {
-  $schema = array();
-  $schema['shurly'] = array(
+  $schema = [];
+  $schema['shurly'] = [
     'description' => t('URL redirects for the Shurly module.'),
-    'fields' => array(
-      'rid' => array(
+    'fields' => [
+      'rid' => [
         'description' => t('Unique redirect id.'),
         'type' => 'serial',
         'not null' => TRUE,
-      ),
-      'uid' => array(
+      ],
+      'uid' => [
         'description' => t('User id of owner.'),
         'type' => 'int',
         'not null' => TRUE,
         'default' => 0,
-      ),
-      'source' => array(
+      ],
+      'source' => [
         'description' => t('Source path.'),
         'type' => 'varchar',
         'length' => '255',
         'binary' => TRUE,
         'not null' => TRUE,
-      ),
-      'destination' => array(
+      ],
+      'destination' => [
         'description' => t('Redirect URL.'),
         'type' => 'text',
         'not null' => TRUE,
-      ),
-      'hash' => array(
+      ],
+      'hash' => [
         'description' => t('The hash of the redirect URL.'),
         'type' => 'varchar',
         'length' => '32',
         'not null' => TRUE,
         'default' => '',
-      ),
-      'created' => array(
+      ],
+      'created' => [
         'description' => t('Datestamp of creation.'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-      'count' => array(
+      ],
+      'count' => [
         'description' => t('Usage count.'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-      'last_used' => array(
+      ],
+      'last_used' => [
         'description' => t('Datestamp of last use.'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-      'custom' => array(
+      ],
+      'custom' => [
         'description' => t('Flag for custom path.'),
         'type' => 'int',
         'not null' => TRUE,
         'default' => 0,
-      ),
-      'active' => array(
+      ],
+      'active' => [
         'description' => t('Allows links to be deactivated.'),
         'type' => 'int',
         'not null' => TRUE,
         'default' => 1,
-      ),
-    ),
-    'primary key' => array('rid'),
-    'indexes' => array(
-      'source' => array('source'),
-      'hash' => array('hash'),
-    ),
-  );
+      ],
+    ],
+    'primary key' => ['rid'],
+    'indexes' => [
+      'source' => ['source'],
+      'hash' => ['hash'],
+    ],
+  ];
 
   // History table to shurly to allow editing of short urls
-  $schema['shurly_history'] = array(
+  $schema['shurly_history'] = [
     'description' => t('Stores a history of the various shortlinks.  Rows are created when they are edited, so we can see what a row once was.'),
-    'fields' => array(
-      'hid' => array(
+    'fields' => [
+      'hid' => [
         'description' => t('Unique history ID.'),
         'type' => 'serial',
         'not null' => TRUE,
-      ),
-      'rid' => array(
+      ],
+      'rid' => [
         'description' => t('The redirect ID.'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-      'vid' => array(
+      ],
+      'vid' => [
         'description' => t('The version for the change made.'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-      'source' => array(
+      ],
+      'source' => [
         'description' => t('Source path.'),
         'type' => 'varchar',
         'length' => '255',
         'binary' => TRUE,
         'not null' => TRUE,
-      ),
-      'destination' => array(
+      ],
+      'destination' => [
         'description' => t('Redirect URL.'),
         'type' => 'text',
         'not null' => TRUE,
-      ),
-      'last_date' => array(
+      ],
+      'last_date' => [
         'description' => t('Datestamp that this link was edited from the value in this row.'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-      'count' => array(
+      ],
+      'count' => [
         'description' => t('Usage count.'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-    ),
-    'primary key' => array('hid'),
-    'indexes' => array(
-      'source' => array('rid', 'vid'),
-    ),
-  );
+      ],
+    ],
+    'primary key' => ['hid'],
+    'indexes' => [
+      'source' => ['rid', 'vid'],
+    ],
+  ];
 
-  $schema['shurly_flood'] = array(
+  $schema['shurly_flood'] = [
     'description' => t('Flood controls the threshold of events, such as the number of contact attempts.'),
-    'fields' => array(
-      'fid' => array(
+    'fields' => [
+      'fid' => [
         'description' => t('Unique flood event ID.'),
         'type' => 'serial',
         'not null' => TRUE,
-      ),
-      'event' => array(
+      ],
+      'event' => [
         'description' => t('Name of event (e.g. contact).'),
         'type' => 'varchar',
         'length' => 64,
         'not null' => TRUE,
         'default' => '',
-      ),
-      'identifier' => array(
+      ],
+      'identifier' => [
         'description' => t('Identifier of the visitor, such as an IP address or hostname.'),
         'type' => 'varchar',
         'length' => 128,
         'not null' => TRUE,
         'default' => '',
-      ),
-      'timestamp' => array(
+      ],
+      'timestamp' => [
         'description' => t('Timestamp of the event.'),
         'type' => 'int',
         'not null' => TRUE,
         'default' => 0,
-      ),
-      'expiration' => array(
+      ],
+      'expiration' => [
         'description' => t('Expiration timestamp. Expired events are purged on cron run.'),
         'type' => 'int',
         'not null' => TRUE,
         'default' => 0,
-      ),
-    ),
-    'primary key' => array('fid'),
-    'indexes' => array(
-      'allow' => array('event', 'identifier', 'timestamp'),
-    ),
-  );
+      ],
+    ],
+    'primary key' => ['fid'],
+    'indexes' => [
+      'allow' => ['event', 'identifier', 'timestamp'],
+    ],
+  ];
 
   return $schema;
 }
 
 /**
  * Implements hook_install().
- * Set the default value of Shurly base URL.
  */
 function shurly_install() {
-  global $base_url;
-
-  \Drupal::configFactory()->getEditable('shurly.settings')
-    ->set('shurly_base', $base_url)
-    ->save();
 }
 
 /**
@@ -188,9 +182,24 @@ function shurly_install() {
 function shurly_uninstall() {
 
   // Remove variables.
-  \Drupal::configFactory()->getEditable('shurly.settings')->clear('shurly_throttle')->save();
-  \Drupal::configFactory()->getEditable('shurly.settings')->clear('shurly_length')->save();
-  \Drupal::configFactory()->getEditable('shurly.settings')->clear('shurly_counter')->save();
-  \Drupal::configFactory()->getEditable('shurly.settings')->clear('shurly_index')->save();
-  \Drupal::configFactory()->getEditable('shurly.settings')->clear('shurly_base')->save();
+  \Drupal::configFactory()
+    ->getEditable('shurly.settings')
+    ->clear('shurly_throttle')
+    ->save();
+  \Drupal::configFactory()
+    ->getEditable('shurly.settings')
+    ->clear('shurly_length')
+    ->save();
+  \Drupal::configFactory()
+    ->getEditable('shurly.settings')
+    ->clear('shurly_counter')
+    ->save();
+  \Drupal::configFactory()
+    ->getEditable('shurly.settings')
+    ->clear('shurly_index')
+    ->save();
+  \Drupal::configFactory()
+    ->getEditable('shurly.settings')
+    ->clear('shurly_base')
+    ->save();
 }
diff --git a/shurly.js b/shurly.js
index 219c29b..10ad540 100755
--- a/shurly.js
+++ b/shurly.js
@@ -1,26 +1,26 @@
-(function($){
-$(document).ready(function(){
-  if ($('#edit-result').length) {
-    var clip = new ZeroClipboard.Client();
-    clip.setText($('#edit-result').val());
-    clip.setHandCursor( true );
-    clip.glue('shurly-copy', 'shurly-copy-container');
-    var origBg = $('#edit-result').css('backgroundColor');
-    clip.addEventListener( 'onComplete', function() {
-      $('#edit-result').css('backgroundColor', '#FFFF3F').fadeTo(300, .1, function(){
-        $(this).fadeTo(1, 1).css('backgroundColor', origBg);
+(function ($) {
+  $(document).ready(function () {
+    if ($('#edit-result').length) {
+      var clip = new ZeroClipboard.Client();
+      clip.setText($('#edit-result').val());
+      clip.setHandCursor(true);
+      clip.glue('shurly-copy', 'shurly-copy-container');
+      var origBg = $('#edit-result').css('backgroundColor');
+      clip.addEventListener('onComplete', function () {
+        $('#edit-result').css('backgroundColor', '#FFFF3F').fadeTo(300, .1, function () {
+          $(this).fadeTo(1, 1).css('backgroundColor', origBg);
+        });
       });
-    });
-    
-    $('#edit-result')
-      .focus()
-      .focus(function(){
-        $(this).select();
-      })
-      .mouseup(function(){
-        // fix for select problem in WebKit
-        return false;
-      });
-  }
-});
+
+      $('#edit-result')
+          .focus()
+          .focus(function () {
+            $(this).select();
+          })
+          .mouseup(function () {
+            // fix for select problem in WebKit
+            return false;
+          });
+    }
+  });
 })(jQuery);
diff --git a/shurly.links.menu.yml b/shurly.links.menu.yml
index 2fca307..4549fb8 100755
--- a/shurly.links.menu.yml
+++ b/shurly.links.menu.yml
@@ -1,5 +1,11 @@
 shurly.admin:
   title: 'ShURLy'
+  description: 'ShURLy configuration and short URLs.'
+  parent: system.admin_config_search
+  route_name: shurly.admin
+
+shurly.settings:
+  title: 'ShURLy settings'
   description: 'Configure base URL, rate limits and more.'
-  parent: system.admin_config_system
+  parent: shurly.admin
   route_name: shurly.settings
\ No newline at end of file
diff --git a/shurly.module b/shurly.module
index f5f1518..afb1b73 100755
--- a/shurly.module
+++ b/shurly.module
@@ -8,7 +8,8 @@
  *   - click to copy link as a Views field
  *   - add some watchdog logging
  *   - remove "http://" from the long URL field when you click in
- *   - add hook for other modules to create additional/substitute long URL validation
+ *   - add hook for other modules to create additional/substitute long URL
+ *   validation
  *   - add option/permission to reactivate URLs
  */
 
@@ -22,7 +23,7 @@ use Drupal\Core\Routing\RouteMatchInterface;
  * Implements hook_page_attachments().
  */
 function shurly_page_attachments(array &$attachments) {
-  if (\Drupal::routeMatch()->getRouteName() == 'shurly.create') {
+  if (Drupal::routeMatch()->getRouteName() == 'shurly.create') {
     $attachments['#attached']['library'][] = 'shurly/clipboardjs';
     $attachments['#attached']['library'][] = 'shurly/shurly';
   }
@@ -43,11 +44,11 @@ function shurly_help($route_name, RouteMatchInterface $route_match) {
  * Implements hook_theme().
  */
 function shurly_theme($existing, $type, $theme, $path) {
-  return array(
-    'shurly_create_form' => array(
+  return [
+    'shurly_create_form' => [
       'render element' => 'form',
-    ),
-  );
+    ],
+  ];
 }
 
 
@@ -56,25 +57,27 @@ function shurly_theme($existing, $type, $theme, $path) {
  *
  * Parameters:
  * $num - your decimal integer
- * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62))
- * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu")
+ * $base - base to which you wish to convert $num (leave it 0 if you are
+ * providing $index or omit if you're using default (62))
+ * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit
+ * this option, otherwise provide a string (ex.: "zyxwvu")
  */
-function shurly_dec2any($num, $base=62, $index=FALSE) {
-    if (! $base ) {
-        $base = strlen( $index );
-    }
-    elseif (! $index ) {
-        // note: we could rearrange this string to get more random looking URLs
-        // another note, to create printable URLs, omit the following characters: 01lIO
-        $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base );
-    }
-    $out = "";
-    for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) {
-        $a = floor( $num / pow( $base, $t ) );
-        $out = $out . substr( $index, $a, 1 );
-        $num = $num - ( $a * pow( $base, $t ) );
-    }
-    return $out;
+function shurly_dec2any($num, $base = 62, $index = FALSE) {
+  if (!$base) {
+    $base = strlen($index);
+  }
+  elseif (!$index) {
+    // note: we could rearrange this string to get more random looking URLs
+    // another note, to create printable URLs, omit the following characters: 01lIO
+    $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base);
+  }
+  $out = "";
+  for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
+    $a = floor($num   / pow($base, $t));
+    $out = $out . substr($index, $a, 1);
+    $num = $num - ($a * pow($base, $t));
+  }
+  return $out;
 }
 
 
@@ -88,7 +91,9 @@ function shurly_dec2any($num, $base=62, $index=FALSE) {
  */
 function shurly_cron() {
   // Cleanup the flood.
-  \Drupal::database()->query('DELETE FROM {shurly_flood} WHERE expiration < :time', array('time' => time()));
+  Drupal::database()->delete('shurly_flood')
+    ->condition('expiration', time(), '<')
+    ->execute();
 }
 
 /**
@@ -96,12 +101,18 @@ function shurly_cron() {
  */
 function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) {
   if (!isset($identifier)) {
-    $identifier = \Drupal::request()->getClientIp();
+    $identifier = Drupal::request()->getClientIp();
   }
 
-  $request_time = \Drupal::time()->getRequestTime();
+  $request_time = Drupal::time()->getRequestTime();
 
-  \Drupal::database()->query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES (:event, :identifier, :timestamp, :expiration)", array('event' => $name, 'identifier' => \Drupal::request()->getClientIp(), 'timestamp' => $request_time, 'expiration' => time() + $window));
+  Drupal::database()
+    ->query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES (:event, :identifier, :timestamp, :expiration)", [
+      'event' => $name,
+      'identifier' => Drupal::request()->getClientIp(),
+      'timestamp' => $request_time,
+      'expiration' => time() + $window,
+    ]);
 }
 
 /**
@@ -113,9 +124,15 @@ function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier
     $identifier = \Drupal::request()->getClientIp();
   }
 
-  $request_time = \Drupal::time()->getRequestTime();
+  $request_time = Drupal::time()->getRequestTime();
 
-  $number = \Drupal::database()->query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array('event' => $name, 'identifier' => $identifier, 'timestamp' => $request_time - $window))->fetchField();
+  $number = Drupal::database()
+    ->query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", [
+      'event' => $name,
+      'identifier' => $identifier,
+      'timestamp' => $request_time - $window,
+    ])
+    ->fetchField();
   return ($number < $threshold);
 }
 
@@ -136,20 +153,22 @@ function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier
  *   'short_url' => the short url
  */
 function shurly_shorten($long_url, $custom = NULL, $account = NULL) {
-  global $base_url;
   $success = FALSE;
-  $account = ($account) ? $account : \Drupal::currentUser();
+  $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.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']));
+    $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->uid);
+    $latest = shurly_get_latest_short($long_url, $account->id());
     if ($latest) {
       $no_save = TRUE;
       $success = TRUE;
@@ -178,12 +197,12 @@ function shurly_shorten($long_url, $custom = NULL, $account = NULL) {
       $error = t('Unknown database error.');
     }
   }
-return array(
+  return [
     'success' => $success,
     'error' => $error,
     'longUrl' => $long_url,
-    'shortUrl' => isset($short) ? _surl($short, array('absolute' => TRUE)) : '',
-  );
+    'shortUrl' => isset($short) ? _surl($short, ['absolute' => TRUE]) : '',
+  ];
 }
 
 /**
@@ -195,7 +214,10 @@ function shurly_expand($short, $account = NULL) {
   $success = 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.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']));
+    $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', [
+      '@rate' => $rate_limit['rate'],
+      '@time' => $rate_limit['time'],
+    ]);
   }
   elseif ($redirect = shurly_get_redirect($short, TRUE)) {
     $success = TRUE;
@@ -205,12 +227,12 @@ function shurly_expand($short, $account = NULL) {
     $error = t('Not found');
   }
 
-  return array(
-      'success' => $success,
-      'error' => $error,
-      'longUrl' => $long_url,
-      'shortUrl' => _surl($short, array('absolute' => TRUE))
-    );
+  return [
+    'success' => $success,
+    'error' => $error,
+    'longUrl' => $long_url,
+    'shortUrl' => _surl($short, ['absolute' => TRUE]),
+  ];
 }
 
 /**
@@ -224,22 +246,23 @@ function shurly_expand($short, $account = NULL) {
  */
 function shurly_rate_limit_allowed($account = NULL) {
   if (!isset($account)) {
-    $user = \Drupal::currentUser();
-    $account = $user;
+    $account = Drupal::currentUser();
   }
 
   // @FIXME
-// Could not extract the default value because it is either indeterminate, or
-// not scalar. You'll need to provide a default value in
-// config/install/shurly.settings.yml and config/schema/shurly.schema.yml.
-$settings = \Drupal::config('shurly.settings')->get('shurly_throttle');
-
-  if (is_array($account->roles)) {
-    $rids = array_keys($account->roles);
+  // Could not extract the default value because it is either indeterminate, or
+  // not scalar. You'll need to provide a default value in
+  // config/install/shurly.settings.yml and config/schema/shurly.schema.yml.
+  $settings = Drupal::config('shurly.settings')->get('shurly_throttle');
+  // Get the roles of a user.
+  $roles = $account->getRoles();
+
+  if (is_array($roles)) {
+    $rids = array_keys($roles);
     $use_rid = array_shift($rids);
-    // get list of roles with permission to create short URLs
+    // Get list of roles with permission to create short URLs.
     $creating_roles = user_roles(FALSE, 'Create short URLs');
-    foreach ($account->roles as $rid => $name) {
+    foreach ($roles as $rid => $name) {
       // check that this role has permission to create URLs, otherwise discard it
       if (array_key_exists($rid, $creating_roles)) {
         // find the lightest role... if roles are the same weight, use the next role
@@ -258,17 +281,17 @@ $settings = \Drupal::config('shurly.settings')->get('shurly_throttle');
     $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60);
     // increment the counter
     shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60);
-    $return = array(
+    $return = [
       'allowed' => $allowed,
       'rate' => $settings[$use_rid]['rate'],
       'time' => $settings[$use_rid]['time'],
-    );
+    ];
   }
   else {
     // not set... don't do a flood check
-    $return = array(
+    $return = [
       'allowed' => TRUE,
-    );
+    ];
   }
 
   return $return;
@@ -279,25 +302,23 @@ $settings = \Drupal::config('shurly.settings')->get('shurly_throttle');
  * @arg $custom is a TRUE/FALSE
  */
 function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) {
-
-  if (is_null($account)) {
-    $account = new stdClass();
-    $account->id = \Drupal::currentUser()->id();
+  if (empty($account)) {
+    $account = Drupal::currentUser();
   }
 
-  $request_time = \Drupal::time()->getRequestTime();
+  $request_time = Drupal::time()->getRequestTime();
 
-  $record = array();
+  $record = [];
   $record['destination'] = $long_url;
   $record['hash'] = md5($long_url);
   $record['custom'] = $custom ? 1 : 0;
   $record['created'] = $request_time;
   $record['source'] = $short_path;
-  $record['uid'] = $account->id;
+  $record['uid'] = $account->id();
   $record['count'] = $record['last_used'] = 0;
   $record['active'] = 1;
 
-  return \Drupal::database()->insert('shurly')->fields($record)->execute();
+  return Drupal::database()->insert('shurly')->fields($record)->execute();
 
 }
 
@@ -306,11 +327,16 @@ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL
  * Activate or deactivate a link
  */
 function shurly_set_link_active($rid, $active) {
-  $record = \Drupal::database()->query('SELECT * FROM {shurly} WHERE rid = :rid', ['rid' => $rid])->fetchObject();
+  $record = Drupal::database()
+    ->query('SELECT * FROM {shurly} WHERE rid = :rid', ['rid' => $rid])
+    ->fetchObject();
   if ($record) {
     $rid = $record->rid;
     $active = $active ? 1 : 0;
-    return \Drupal::database()->merge('shurly')->fields(['rid' => $rid, 'active' => $active ])->key(['rid' => $rid])->execute();
+    return Drupal::database()->merge('shurly')->fields([
+      'rid' => $rid,
+      'active' => $active,
+    ])->key(['rid' => $rid])->execute();
   }
   else {
     return FALSE;
@@ -324,12 +350,13 @@ function shurly_set_link_active($rid, $active) {
  */
 function shurly_validate_custom($custom) {
 
-  // check the length of the string
+  // Check the length of the string.
   if (strlen($custom) == 0) {
     return FALSE;
   }
 
   // disallow: #%&@*{}\:;<>?/+.,'"$|`^[] and space character
+//  return preg_match('/[#%&\@\*\{\}\\:\;<>\?\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE;
   return preg_match('/[\/#%&\@\*\{\}\\:\;<>\?\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE;
 }
 
@@ -356,10 +383,13 @@ function shurly_validate_long(&$long_url) {
   $long_parse = parse_url($long_url);
   $base_parse = parse_url($GLOBALS['base_url']);
 
-  $check_ip = \Drupal::config('shurly.settings')->get('shurly_forbid_ips');
-  $check_localhost = \Drupal::config('shurly.settings')->get('shurly_forbid_localhost');
-  $check_resolvability = \Drupal::config('shurly.settings')->get('shurly_forbid_unresolvable_hosts');
-  $check_private_ip_ranges = \Drupal::config('shurly.settings')->get('shurly_forbid_private_ips');
+  $check_ip = Drupal::config('shurly.settings')->get('shurly_forbid_ips');
+  $check_localhost = Drupal::config('shurly.settings')
+    ->get('shurly_forbid_localhost');
+  $check_resolvability = Drupal::config('shurly.settings')
+    ->get('shurly_forbid_unresolvable_hosts');
+  $check_private_ip_ranges = Drupal::config('shurly.settings')
+    ->get('shurly_forbid_private_ips');
 
   if ($long_parse === FALSE || !isset($long_parse['host'])) {
     // malformed URL
@@ -388,8 +418,9 @@ function shurly_validate_long(&$long_url) {
     $return = FALSE;
   }
   else {
-    if (\Drupal::config('shurly.settings')->get('shurly_forbid_custom')) {
-      $custom_pattern = \Drupal::config('shurly.settings')->get('shurly_custom_restriction');
+    if (Drupal::config('shurly.settings')->get('shurly_forbid_custom')) {
+      $custom_pattern = Drupal::config('shurly.settings')
+        ->get('shurly_custom_restriction');
       if (!empty($custom_pattern)) {
         if (preg_match($custom_pattern, $long_url)) {
           $return = FALSE;
@@ -428,12 +459,12 @@ function shurly_validate_long(&$long_url) {
       // by the way, we're ignoring any subdomain...
       // so http://lbt.me/something and http://www.lbt.me/something are assumed to be the same
       if ($match) {
-        $queries  = array();
-        if(isset($long_parse['query'])){
+        $queries = [];
+        if (isset($long_parse['query'])) {
           // let's see if there's a $_GET['q'] in the long URL
           $query = $long_parse['query'];
-          $query  = html_entity_decode($query);
-          $query_array  = explode('&', $query);
+          $query = html_entity_decode($query);
+          $query_array = explode('&', $query);
           foreach ($query_array as $val) {
             $x = explode('=', $val);
             $queries[$x[0]] = $x[1];
@@ -477,13 +508,13 @@ function shurly_validate_long(&$long_url) {
  */
 function shurly_generate_random($len = NULL) {
   if ($len == NULL) {
-    $len = \Drupal::config('shurly.settings')->get('shurly_length');
+    $len = Drupal::config('shurly.settings')->get('shurly_length');
   }
   $charset = "abcdefghijklmnopqrstuvwxyz123456789";
   $charlen = strlen($charset) - 1;
   do {
     $str = '';
-    for ($i=0; $i<$len; $i++) {
+    for ($i = 0; $i < $len; $i++) {
       $str .= $charset[mt_rand(0, $charlen)];
     }
     // check that this string hasn't been used already
@@ -491,7 +522,7 @@ function shurly_generate_random($len = NULL) {
   } while (shurly_url_exists($str) || !shurly_path_available($str));
 
   // allow extra operations
-  \Drupal::moduleHandler()->invokeAll('shurly_shorturl_extra', [$str]);
+  Drupal::moduleHandler()->invokeAll('shurly_shorturl_extra', [$str]);
 
   return $str;
 }
@@ -501,33 +532,39 @@ function shurly_generate_random($len = NULL) {
  */
 function shurly_next_url() {
 
-  $count = \Drupal::config('shurly.settings')->get('shurly_counter'); // starts the URLs with 3 characters
+  $count = Drupal::config('shurly.settings')
+    ->get('shurly_counter'); // starts the URLs with 3 characters
+
   do {
     $count++;
     // counter is stored as base 10
     // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters
     // a custom index can be created as a variable override in settings.php
-    $index = \Drupal::config('shurly.settings')->get('shurly_index');
+    $index = Drupal::config('shurly.settings')->get('shurly_index');
     $str = shurly_dec2any($count, NULL, $index);
 
     // check that this string hasn't been used already
     // check that the string is a valid (available) path
   } while (shurly_url_exists($str) !== FALSE || shurly_path_available($str) === FALSE);
 
-  \Drupal::configFactory()->getEditable('shurly.settings')->set('shurly_counter', $count)->save();
+  Drupal::configFactory()
+    ->getEditable('shurly.settings')
+    ->set('shurly_counter', $count)
+    ->save();
 
   return $str;
 }
 
 /**
- * Checks to see if there's a menu handler, path alias, or language prefix for a given path
+ * Checks to see if there's a menu handler, path alias, or language prefix for
+ * a given path
  *
  * @return TRUE if there are no conflicts
  */
 function shurly_path_available($path) {
 
   // check to see if path represents an enabled language
-  $languages =  \Drupal::LanguageManager()->getLanguages();
+  $languages = Drupal::LanguageManager()->getLanguages();
   if (array_key_exists($path, $languages)) {
     return FALSE;
   }
@@ -535,17 +572,17 @@ function shurly_path_available($path) {
   $return = TRUE;
 
   // see if $path is an alias
-  $source = \Drupal::service('path.alias_manager')->getAliasByPath('/'.$path);
+  $source = Drupal::service('path.alias_manager')->getAliasByPath('/' . $path);
   if ($source != $path) {
     // if so, set alias source to $path
     $path = $source;
   }
 
-  $url_object = \Drupal::service('path.validator')->getUrlIfValid($path);
+  $url_object = Drupal::service('path.validator')->getUrlIfValid($path);
 
   if ($url_object) {
-      $return = FALSE;
-    }
+    $return = FALSE;
+  }
 
   return $return;
 }
@@ -574,7 +611,9 @@ function shurly_get_redirect($short_url, $check_active = FALSE) {
   if ($check_active) {
     $query .= ' AND active = 1';
   }
-  $redirect = \Drupal::database()->query($query, array('short' => $short_url))->fetchObject();
+  $redirect = Drupal::database()
+    ->query($query, ['short' => $short_url])
+    ->fetchObject();
   return $redirect;
 }
 
@@ -583,28 +622,49 @@ function shurly_get_redirect($short_url, $check_active = FALSE) {
  */
 function shurly_get_latest_short($long, $uid) {
   $hash = md5($long);
-  return \Drupal::database()->query("SELECT source FROM {shurly} WHERE hash = :hash AND uid = :uid AND custom = 0 AND active = 1 ORDER BY rid DESC LIMIT 1", array('hash' => $hash, 'uid' => $uid))->fetchField();;
+  return Drupal::database()
+    ->query("SELECT source FROM {shurly} WHERE hash = :hash AND uid = :uid AND custom = 0 AND active = 1 ORDER BY rid DESC LIMIT 1", [
+      'hash' => $hash,
+      'uid' => $uid,
+    ])
+    ->fetchField();;
 }
 
 /**
- * Internal function to format a URL without language prefixing or subdomain rewrites
+ * Internal function to format a URL without language prefixing or subdomain
+ * rewrites
  */
-function _surl($path = NULL, $options = array()) {
-  $shurly_base = \Drupal::config('shurly.settings')->get('shurly_base');
+function _surl($path = NULL, $options = []) {
+  $shurly_base = _shurly_get_shurly_base();
 
   //Set default language object which will avoid redirects and subdomains
   $options['language'] = Language::$defaultValues;
 
-  return Url::fromUri($shurly_base. '/' . $path, $options)->toString();
+  return Url::fromUri($shurly_base . '/' . $path, $options)->toString();
 }
 
 /**
- * Internal function to generate a link without language prefixing or subdomain rewrites
+ * Internal function to generate a link without language prefixing or subdomain
+ * rewrites
  */
-function _sl($text, $path, $options = array()) {
-  $shurly_base = \Drupal::config('shurly.settings')->get('shurly_base');
+function _sl($text, $path, $options = []) {
+  $shurly_base = _shurly_get_shurly_base();
+
+  return Link::fromTextAndUrl($text, Url::fromUri($shurly_base . '/' . $path, $options))
+    ->toString();
+}
 
-  return Link::fromTextAndUrl($text, Url::fromUri($shurly_base. '/' . $path, $options))->toString();
+/**
+ * Return the base url used for the shortlinks.
+ *
+ * @return string
+ */
+function _shurly_get_shurly_base() {
+  $shurly_base = trim(Drupal::config('shurly.settings')->get('shurly_base'));
+  if (empty($shurly_base)) {
+    $shurly_base = Drupal::request()->getSchemeAndHttpHost();
+  }
+  return $shurly_base;
 }
 
 
@@ -624,7 +684,7 @@ function _sl($text, $path, $options = array()) {
  *   Resolved host address on success or the input $hostname on failure.
  */
 function _shurly_gethostbyname($hostname) {
-  static $resolved_hosts = array();
+  static $resolved_hosts = [];
 
   if (!isset($resolved_hosts[$hostname])) {
     $resolved_hosts[$hostname] = gethostbyname($hostname);
@@ -724,48 +784,53 @@ function shurly_host_is_private($hostname) {
  *   TRUE if the given URL matches; otherwise FALSE.
  *
  */
-function shurly_gsb($url){
-  $client = \Drupal::config('shurly.settings')->get('shurly_gsb_config_client');
-  $api_key = \Drupal::config('shurly.settings')->get('shurly_gsb_apikey');
-
-  $gsb_url = "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=".$api_key;
-
-  $rawdata = array(
-    'client' => array("clientId" => "lccx", "clientVersion" => "1.5.2"),
-    'threatInfo' => array(
-      "threatTypes" => array("MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"),
-      "platformTypes" => array("ALL_PLATFORMS"),
-      "threatEntryTypes" => array("URL"),
-      "threatEntries" => array(array("url" => $url))
-    )
-  );
+function shurly_gsb($url) {
+  $client = Drupal::config('shurly.settings')->get('shurly_gsb_config_client');
+  $api_key = Drupal::config('shurly.settings')->get('shurly_gsb_apikey');
+
+  $gsb_url = "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=" . $api_key;
+
+  $rawdata = [
+    'client' => ["clientId" => "lccx", "clientVersion" => "1.5.2"],
+    'threatInfo' => [
+      "threatTypes" => [
+        "MALWARE",
+        "SOCIAL_ENGINEERING",
+        "UNWANTED_SOFTWARE",
+        "POTENTIALLY_HARMFUL_APPLICATION",
+      ],
+      "platformTypes" => ["ALL_PLATFORMS"],
+      "threatEntryTypes" => ["URL"],
+      "threatEntries" => [["url" => $url]],
+    ],
+  ];
 
   $data = json_encode($rawdata);
 
-  $client = \Drupal::httpClient();
+  $client = Drupal::httpClient();
   $request = $client->createRequest('POST', $gsb_url, $data);
   $request->addHeader('Content-Type', 'application/json');
 
   try {
     $response = $client->get($gsb_url, [
       'headers' => [
-        'Content-Type', 'application/json',
+        'Content-Type',
+        'application/json',
       ],
     ]);
     $data = json_decode($response->getBody());
 
     if ($data->matches) {
-      return True;
+      return TRUE;
     }
-    else{
-      return False;
+    else {
+      return FALSE;
     }
-  }
-  catch (RequestException $e) {
+  } catch (RequestException $e) {
     watchdog_exception('shurly', $e);
   }
 }
 
 function shurly_disable_url(&$shurly_item, $context) {
-    shurly_set_link_active($shurly_item->rid, 0);
+  shurly_set_link_active($shurly_item->rid, 0);
 }
diff --git a/shurly.routing.yml b/shurly.routing.yml
index 48367c6..9dde766 100755
--- a/shurly.routing.yml
+++ b/shurly.routing.yml
@@ -19,8 +19,16 @@ shurly.deactivate:
     _title: 'Deactivate URL'
   requirements:
     _custom_access: '\Drupal\shurly\Form\ShurlyDeactivateForm::access'
+
+shurly.admin:
+  path: '/admin/config/search/shurly'
+  defaults:
+    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
+    _title: 'Shurly'
+  requirements:
+    _permission: 'administer short URLs'
 shurly.settings:
-  path: '/admin/config/system/shurly'
+  path: '/admin/config/search/shurly/settings'
   defaults:
     _form: '\Drupal\shurly\Form\ShurlySettingsForm'
     _title: 'Settings'
diff --git a/shurly.views.inc b/shurly.views.inc
index e5d89a9..683fab0 100755
--- a/shurly.views.inc
+++ b/shurly.views.inc
@@ -7,219 +7,219 @@
 
 function shurly_views_data() {
 
-  $data = array();
+  $data = [];
 
-  $data['shurly'] = array();
+  $data['shurly'] = [];
 
-  $data['users'] = array();
+  $data['users'] = [];
 
-  $data['users_data'] = array();
+  $data['users_data'] = [];
 
-  $data['users_field_data'] = array();
+  $data['users_field_data'] = [];
 
-  $data['shurly']['table']['group']  = t('Shurly');
+  $data['shurly']['table']['group'] = t('Shurly');
 
   $data['shurly']['table']['provider'] = 'shurly';
 
   // not sure if this is the best way, but it allows to get access to the user fields data
   $data['shurly']['table']['entity type'] = 'user';
 
-  $data['shurly']['table']['base'] = array(
+  $data['shurly']['table']['base'] = [
     'field' => 'rid',
     'title' => t('Short URLs'),
     'help' => t('Shurly shortened URLs.'),
     'weight' => 10,
-  );
+  ];
 
-  $data['users']['table']['join']['shurly'] = array(
+  $data['users']['table']['join']['shurly'] = [
     'left_field' => 'uid',
     'field' => 'uid',
-  );
+  ];
 
-  $data['users_data']['table']['join']['shurly'] = array(
+  $data['users_data']['table']['join']['shurly'] = [
     'left_field' => 'uid',
     'field' => 'uid',
-  );
+  ];
 
-  $data['users_field_data']['table']['join']['shurly'] = array(
+  $data['users_field_data']['table']['join']['shurly'] = [
     'left_field' => 'uid',
     'field' => 'uid',
-  );
+  ];
 
   // User ID
-  $data['shurly']['uid'] = array(
+  $data['shurly']['uid'] = [
     'title' => t('User ID'),
     'help' => t('ID of user who created the link.'),
-    'field' => array(
+    'field' => [
       'id' => 'numeric',
       'click sortable' => TRUE,
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'numeric',
       'name field' => 'name',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'title' => t('Name'),
       'id' => 'numeric',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'standard',
-    ),
-    'relationship' => array(
+    ],
+    'relationship' => [
       'id' => 'standard',
       'base' => 'users',
       'base field' => 'uid',
       'label' => t('user'),
-    ),
-  );
+    ],
+  ];
 
   // uid
-  $data['shurly']['uid_current'] = array(
+  $data['shurly']['uid_current'] = [
     'real field' => 'uid',
     'title' => t('Current user'),
     'help' => t('Filter the view to the currently logged in user.'),
-    'filter' => array(
+    'filter' => [
       'id' => 'user_current',
       'type' => 'yes-no',
-    ),
-  );
+    ],
+  ];
 
   // Shurly Source - Short URL
-  $data['shurly']['source'] = array(
+  $data['shurly']['source'] = [
     'title' => t('Short URL'),
     'help' => t('The source URL which generates a redirect'),
-    'field' => array(
+    'field' => [
       'id' => 'shurly_short_url',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'id' => 'string',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'standard',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'string',
-    ),
-  );
+    ],
+  ];
 
   // Shurly Desination - Long URL
-  $data['shurly']['destination'] = array(
+  $data['shurly']['destination'] = [
     'title' => t('Long URL'),
     'help' => t('The destination URL'),
-    'field' => array(
+    'field' => [
       'id' => 'standard',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'id' => 'string',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'standard',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'string',
-    ),
-  );
+    ],
+  ];
 
   // Link created timestamp
-  $data['shurly']['created'] = array(
+  $data['shurly']['created'] = [
     'title' => t('Created date'),
     'help' => t('The date/time the link was created.'),
-    'field' => array(
+    'field' => [
       'id' => 'date',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'date',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'id' => 'date',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'date',
-    ),
-  );
+    ],
+  ];
 
   // Count
-  $data['shurly']['count'] = array(
+  $data['shurly']['count'] = [
     'title' => t('Clicks'),
     'help' => t('Number of times this link has been followed.'),
-    'field' => array(
+    'field' => [
       'id' => 'numeric',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'id' => 'numeric',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'standard',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'numeric',
-    ),
+    ],
 
-  );
+  ];
 
   // Link last used timestamp
-  $data['shurly']['last_used'] = array(
+  $data['shurly']['last_used'] = [
     'title' => t('Last used date'),
     'help' => t('The last date/time the link was used.'),
-    'field' => array(
+    'field' => [
       'id' => 'date',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'date',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'id' => 'date',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'date',
-    ),
-  );
+    ],
+  ];
 
   // Boolean for custom entry
-  $data['shurly']['custom'] = array(
+  $data['shurly']['custom'] = [
     'title' => t('Custom URL'),
     'help' => t('Boolean flag set for custom short URLs entered by user.'),
-    'field' => array(
+    'field' => [
       'id' => 'boolean',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'standard',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'id' => 'boolean',
       'label' => t('Custom'),
       'type' => 'yes-no',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'boolean',
-    ),
-  );
+    ],
+  ];
 
   // Boolean for active link
-  $data['shurly']['active'] = array(
+  $data['shurly']['active'] = [
     'title' => t('URL active'),
     'help' => t('Is this link active or has it been deactivated?'),
-    'field' => array(
+    'field' => [
       'id' => 'boolean',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'id' => 'standard',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'id' => 'boolean',
       'label' => t('Custom'),
       'type' => 'yes-no',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'id' => 'boolean',
-    ),
-  );
+    ],
+  ];
 
   $data['shurly']['link_edit'] = [
     'title' => t('Edit URL'),
     'help' => t('Link to edit the URL'),
     'field' => [
-      'id' => 'shurly_link_edit'
+      'id' => 'shurly_link_edit',
     ],
   ];
 
@@ -227,7 +227,7 @@ function shurly_views_data() {
     'title' => t('Deactivate URL'),
     'help' => t('Link to deactivate the URL'),
     'field' => [
-      'id' => 'shurly_link_deactivate'
+      'id' => 'shurly_link_deactivate',
     ],
   ];
 
diff --git a/shurly_analytics/config/schema/shurly_analytics.schema.yml b/shurly_analytics/config/schema/shurly_analytics.schema.yml
index b1bcc69..d3dcb7b 100755
--- a/shurly_analytics/config/schema/shurly_analytics.schema.yml
+++ b/shurly_analytics/config/schema/shurly_analytics.schema.yml
@@ -3,4 +3,4 @@ shurly_analytics.settings:
   label: Settings
   mapping:
     shurly_analytics_account:
-     type: string
+      type: string
diff --git a/shurly_analytics/shurly_analytics.module b/shurly_analytics/shurly_analytics.module
index 18b5630..3707305 100755
--- a/shurly_analytics/shurly_analytics.module
+++ b/shurly_analytics/shurly_analytics.module
@@ -9,76 +9,85 @@
 /**
  * Implements shurly_redirect_after().
  */
-function shurly_analytics_shurly_redirect_after($row){
-  if(\Drupal::config('google_analytics.settings')->get('account')){
-      $ga_id = \Drupal::config('shurly_analytics.settings')->get('shurly_ga_account');
-      $cid = _shurly_analytics_cookies();
-      $path_args = explode('/', \Drupal::request()->getPathInfo());
-      $path = "/".$path_args[1];
-      $destination = $row->destination;
-      $z =  microtime(true);
+function shurly_analytics_shurly_redirect_after($row) {
+  if (\Drupal::config('google_analytics.settings')->get('account')) {
+    $ga_id = \Drupal::config('shurly_analytics.settings')
+      ->get('shurly_ga_account');
+    $cid = _shurly_analytics_cookies();
+    $path_args = explode('/', \Drupal::request()->getPathInfo());
+    $path = "/" . $path_args[1];
+    $destination = $row->destination;
+    $z = microtime(TRUE);
 
-      $data = array(
-                'v' => 1,
-                'tid' => $ga_id,
-                'cid' => $cid,
-                'uip' => $_SERVER['REMOTE_ADDR'],
-                't' => 'pageview',
-                'dh' => $_SERVER['SERVER_NAME'],
-                'dl' => $destination,
-                'dp' => $path,
-                'aip' => 1,
-                'dr' => $_SERVER['HTTP_REFERER'],
-                'z' => $z,
-      );
+    $data = [
+      'v' => 1,
+      'tid' => $ga_id,
+      'cid' => $cid,
+      'uip' => $_SERVER['REMOTE_ADDR'],
+      't' => 'pageview',
+      'dh' => $_SERVER['SERVER_NAME'],
+      'dl' => $destination,
+      'dp' => $path,
+      'aip' => 1,
+      'dr' => $_SERVER['HTTP_REFERER'],
+      'z' => $z,
+    ];
 
-      if($data) {
-        $getString = 'https://ssl.google-analytics.com/collect';
-        $getString .= '?payload_data&';
-        $getString .= http_build_query($data);
+    if ($data) {
+      $getString = 'https://ssl.google-analytics.com/collect';
+      $getString .= '?payload_data&';
+      $getString .= http_build_query($data);
 
-        $request = file_get_contents($getString, false);
-        if($request){
-          return;
-        }
+      $request = file_get_contents($getString, FALSE);
+      if ($request) {
         return;
+      }
+      return;
     }
   }
 }
 
 /**
  * Function to retrieve the cid from the cookie
- * Taken from http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
+ * Taken from
+ * http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
  */
 function _shurly_analytics_cookies() {
   if (isset($_COOKIE['_ga'])) {
-     list($version, $domainDepth, $cid1, $cid2) = preg_split('/[\.]/', $_COOKIE['_ga'], 4);
-     $contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1 . '.' . $cid2);
+    list($version, $domainDepth, $cid1, $cid2) = preg_split('/[\.]/', $_COOKIE['_ga'], 4);
+    $contents = [
+      'version' => $version,
+      'domainDepth' => $domainDepth,
+      'cid' => $cid1 . '.' . $cid2,
+    ];
     $cid = $contents['cid'];
   }
-  else $cid = _shurly_analytics_get_uuid();
+  else {
+    $cid = _shurly_analytics_get_uuid();
+  }
 
   return $cid;
 }
 
 /**
  * Function to get a unique uuid
- * Taken from http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
+ * Taken from
+ * http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
  */
-function _shurly_analytics_get_uuid(){
-  return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
+function _shurly_analytics_get_uuid() {
+  return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
     // 32 bits for "time_low"
-    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
+    mt_rand(0, 0xffff), mt_rand(0, 0xffff),
     // 16 bits for "time_mid"
-    mt_rand( 0, 0xffff ),
+    mt_rand(0, 0xffff),
     // 16 bits for "time_hi_and_version",
     // four most significant bits holds version number 4
-    mt_rand( 0, 0x0fff ) | 0x4000,
+    mt_rand(0, 0x0fff) | 0x4000,
     // 16 bits, 8 bits for "clk_seq_hi_res",
     // 8 bits for "clk_seq_low",
     // two most significant bits holds zero and one for variant DCE1.1
-    mt_rand( 0, 0x3fff ) | 0x8000,
+    mt_rand(0, 0x3fff) | 0x8000,
     // 48 bits for "node"
-    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
-    );
+    mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
+  );
 }
diff --git a/shurly_analytics/src/Form/ShurlyAnalyticsSettingsForm.php b/shurly_analytics/src/Form/ShurlyAnalyticsSettingsForm.php
index f32a419..1fdb829 100755
--- a/shurly_analytics/src/Form/ShurlyAnalyticsSettingsForm.php
+++ b/shurly_analytics/src/Form/ShurlyAnalyticsSettingsForm.php
@@ -12,12 +12,13 @@ use Drupal\Core\Form\ConfigFormBase;
 use Drupal\Core\Render\Element;
 
 class ShurlyAnalyticsSettingsForm extends ConfigFormBase {
+
   /**
    * {@inheritdoc}
    */
-   public function __construct(ConfigFactoryInterface $config_factory) {
-     parent::__construct($config_factory);
-   }
+  public function __construct(ConfigFactoryInterface $config_factory) {
+    parent::__construct($config_factory);
+  }
 
   /**
    * {@inheritdoc}
@@ -36,14 +37,15 @@ class ShurlyAnalyticsSettingsForm extends ConfigFormBase {
   public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
     global $base_url;
 
-    $form['shurlyanalytics_account'] = array(
-        '#title' => t('Enter you Identifiant (ID) Web Property'),
-        '#type' => 'textfield',
-        '#default_value' => \Drupal::config('google_analytics.settings')->get('account'),
-        '#size' => 15,
-        '#maxlength' => 20,
-        '#required' => TRUE,
-      );
+    $form['shurlyanalytics_account'] = [
+      '#title' => t('Enter you Identifiant (ID) Web Property'),
+      '#type' => 'textfield',
+      '#default_value' => \Drupal::config('google_analytics.settings')
+        ->get('account'),
+      '#size' => 15,
+      '#maxlength' => 20,
+      '#required' => TRUE,
+    ];
 
     return parent::buildForm($form, $form_state);
   }
diff --git a/shurly_service/shurly_api_keys.inc b/shurly_service/shurly_api_keys.inc
index 19e5373..91323b1 100755
--- a/shurly_service/shurly_api_keys.inc
+++ b/shurly_service/shurly_api_keys.inc
@@ -8,6 +8,7 @@ define('API_VERSION', 'A');
 
 /**
  * Generate a new api key for this user and put it into the database
+ *
  * @return the new API key or FALSE on database insert error
  */
 function shurly_generate_new_api_key($uid) {
@@ -15,16 +16,25 @@ function shurly_generate_new_api_key($uid) {
   do {
     $key = md5(uniqid(rand(), TRUE)) . '_' . API_VERSION;
   } while (shurly_get_uid($key));
-  \Drupal::database()->query('DELETE FROM {shurly_keys} WHERE uid = :uid', array('uid' => $uid));
-  $result = \Drupal::database()->query("INSERT INTO {shurly_keys} (uid, apikey) VALUES (:uid, :key)", array('uid' => $uid, 'key' => $key));
+  \Drupal::database()
+    ->query('DELETE FROM {shurly_keys} WHERE uid = :uid', ['uid' => $uid]);
+  $result = \Drupal::database()
+    ->query("INSERT INTO {shurly_keys} (uid, apikey) VALUES (:uid, :key)", [
+      'uid' => $uid,
+      'key' => $key,
+    ]);
   return $result ? $key : FALSE;
 }
 
 function shurly_get_uid($key) {
-  return \Drupal::database()->query("SELECT uid FROM {shurly_keys} WHERE apikey = :key", array('key' => $key))->fetchField();
+  return \Drupal::database()
+    ->query("SELECT uid FROM {shurly_keys} WHERE apikey = :key", ['key' => $key])
+    ->fetchField();
 }
 
 function shurly_get_api_key($uid) {
-  return \Drupal::database()->query("SELECT apikey FROM {shurly_keys} WHERE uid = :uid", array('uid' => $uid))->fetchField();
+  return \Drupal::database()
+    ->query("SELECT apikey FROM {shurly_keys} WHERE uid = :uid", ['uid' => $uid])
+    ->fetchField();
 }
 
diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc
index c7e8c08..2ea46f1 100755
--- a/shurly_service/shurly_service.inc
+++ b/shurly_service/shurly_service.inc
@@ -9,19 +9,21 @@
  * Callback for shurly/api/shorten
  */
 function shurly_service_shorten() {
-  $defaults = array(
+  $defaults = [
     'format' => 'json',
     // 'domain' => NULL,
     'longUrl' => '',
     'shortUrl' => NULL,
     'apiKey' => NULL,
     'func' => 'urlData', // function name for padded JSON
-  );
+  ];
   $input = $_GET + $defaults;
 
   module_load_include('inc', 'shurly_service', 'shurly_api_keys');
   $uid = isset($input['apiKey']) ? shurly_get_uid($input['apiKey']) : NULL;
-  $account = $uid ? \Drupal::entityTypeManager()->getStorage('user')->load($uid) : NULL;
+  $account = $uid ? \Drupal::entityTypeManager()
+    ->getStorage('user')
+    ->load($uid) : NULL;
   $access = $account->hasPermission('Create short URLs');
 
   if ($access) {
@@ -33,10 +35,10 @@ function shurly_service_shorten() {
     $data = shurly_shorten($input['longUrl'], $input['shortUrl'], $account);
   }
   else {
-    $data = array(
+    $data = [
       'success' => FALSE,
       'error' => t('Invalid API key'),
-    );
+    ];
   }
   shurly_service_output($data, $input);
 }
@@ -45,7 +47,7 @@ function shurly_service_shorten() {
  * Callback for shurly/api/shorten
  */
 function shurly_service_expand() {
-  $defaults = array(
+  $defaults = [
     'format' => 'json',
     // 'domain' => NULL,
     //'longUrl' => '',
@@ -53,12 +55,14 @@ function shurly_service_expand() {
     // 'login' => NULL,
     'apiKey' => NULL,
     'func' => 'urlData', // function name for padded JSON
-  );
+  ];
   $input = $_GET + $defaults;
 
   module_load_include('inc', 'shurly_service', 'shurly_api_keys');
   $uid = isset($input['apiKey']) ? shurly_get_uid($input['apiKey']) : NULL;
-  $account = $uid ? \Drupal::entityTypeManager()->getStorage('user')->load($uid) : NULL;
+  $account = $uid ? \Drupal::entityTypeManager()
+    ->getStorage('user')
+    ->load($uid) : NULL;
   $access = $account->hasPermission('Expand short URLs');
 
   if ($access) {
@@ -66,10 +70,10 @@ function shurly_service_expand() {
     $data = shurly_expand($path, $account);
   }
   else {
-    $data = array(
+    $data = [
       'success' => FALSE,
       'error' => t('Invalid API key'),
-    );
+    ];
   }
 
   shurly_service_output($data, $input);
@@ -125,7 +129,7 @@ function shurly_service_output_txt($data) {
     print $data[$key];
   }
   else {
-    print t("ERROR: !error", array('!error' => $data['error']));
+    print t("ERROR: !error", ['!error' => $data['error']]);
   }
 }
 
diff --git a/shurly_service/shurly_service.install b/shurly_service/shurly_service.install
index e3144d0..8ed6fec 100755
--- a/shurly_service/shurly_service.install
+++ b/shurly_service/shurly_service.install
@@ -8,25 +8,25 @@
  * Implement hook_schema().
  */
 function shurly_service_schema() {
-  $schema['shurly_keys'] = array(
+  $schema['shurly_keys'] = [
     'description' => t('API keys for use with the Shurly module'),
-    'fields' => array(
-      'uid' => array(
+    'fields' => [
+      'uid' => [
         'description' => t('User ID'),
         'type' => 'int',
         'not null' => TRUE,
-      ),
-      'apikey' => array(
+      ],
+      'apikey' => [
         'description' => t('API key for user'),
         'type' => 'varchar',
         'length' => '35',
         'not null' => TRUE,
-      ),
-    ),
-    'primary key' => array('apikey'),
-    'indexes' => array(
-      'uid' => array('uid'),
-    ),
-  );
+      ],
+    ],
+    'primary key' => ['apikey'],
+    'indexes' => [
+      'uid' => ['uid'],
+    ],
+  ];
   return $schema;
 }
diff --git a/shurly_service/shurly_service.module b/shurly_service/shurly_service.module
index a36f0cb..8eac399 100755
--- a/shurly_service/shurly_service.module
+++ b/shurly_service/shurly_service.module
@@ -12,37 +12,37 @@
  * Implements hook_permission().
  */
 function shurly_service_permission() {
-  return array(
-    'administer short URL services' => array(
+  return [
+    'administer short URL services' => [
       'title' => t('Administer short URL services'),
-    ),
-    'Expand short URLs' => array(
+    ],
+    'Expand short URLs' => [
       'title' => t('Expand short URLs'),
-    ),
-    'Request custom short URL' => array(
+    ],
+    'Request custom short URL' => [
       'title' => t('Request custom short URL'),
       'description' => t('Allow users to pass a desired custom short URL to the shURLy service.'),
-    ),
-  );
+    ],
+  ];
 }
 
 /**
  * Implements hook_menu().
  */
 function shurly_service_menu() {
-  $items = array();
-  $items['shurly/api/shorten'] = array(
+  $items = [];
+  $items['shurly/api/shorten'] = [
     'file' => 'shurly_service.inc',
     'page callback' => 'shurly_service_shorten',
     'access callback' => 'shurly_service_access_api_key',
     'type' => MENU_CALLBACK,
-  );
-  $items['shurly/api/expand'] = array(
+  ];
+  $items['shurly/api/expand'] = [
     'file' => 'shurly_service.inc',
     'page callback' => 'shurly_service_expand',
     'access callback' => TRUE,
     'type' => MENU_CALLBACK,
-  );
+  ];
 
   return $items;
 }
@@ -52,17 +52,18 @@ function shurly_service_access_api_key() {
     module_load_include('inc', 'shurly_service', 'shurly_api_keys');
     $api_validation = (is_numeric(shurly_get_uid($_REQUEST['apiKey']))) ? TRUE : FALSE;
   }
-    
-  return \Drupal::currentUser()->hasPermission('Create short URLs') && $api_validation;
+
+  return \Drupal::currentUser()
+      ->hasPermission('Create short URLs') && $api_validation;
 }
 
 /**
  * Implements hook_block_info().
  */
 function shurly_service_block_info() {
-  $blocks['api_key'] = array(
+  $blocks['api_key'] = [
     'info' => t('Short URL API key'),
-  );
+  ];
   return $blocks;
 }
 
@@ -71,14 +72,16 @@ function shurly_service_block_info() {
  * Implements hook_block_view().
  */
 function shurly_service_block_view($delta = '') {
-  $block = array();
+  $block = [];
   // don't show the block when user is on the callback page
   switch ($delta) {
     case 'api_key':
       $user = \Drupal::currentUser();
-      if ($user->uid > 0 && \Drupal::currentUser()->hasPermission('Create short URLs')) {
+      if ($user->uid > 0 && \Drupal::currentUser()
+          ->hasPermission('Create short URLs')) {
         $block['subject'] = t('API key');
-        $block['content'] = \Drupal::formBuilder()->getForm('shurly_api_key_form');
+        $block['content'] = \Drupal::formBuilder()
+          ->getForm('shurly_api_key_form');
       }
       break;
   }
@@ -93,27 +96,27 @@ function shurly_api_key_form($form, &$form_state) {
   module_load_include('inc', 'shurly_service', 'shurly_api_keys');
   $key = shurly_get_api_key($user->uid);
 
-  $form = array();
+  $form = [];
   if ($key) {
-    $form['key'] = array(
+    $form['key'] = [
       '#type' => 'textfield',
       '#title' => t('API key'),
       '#default_value' => $key,
       '#description' => t('You can provide this key to 3rd party apps rather than sharing your password.'),
-    );
-    $form['reset'] = array(
+    ];
+    $form['reset'] = [
       '#type' => 'submit',
       '#value' => t('Reset'),
       '#suffix' => t('If a 3rd party is misusing your API key, you can generate a new one.'),
-    );
+    ];
 
   }
   else {
-    $form['new'] = array(
+    $form['new'] = [
       '#type' => 'submit',
       '#value' => t('Create'),
-      '#suffix' =>  t('Create an API key to use with 3rd party applications.'),
-    );
+      '#suffix' => t('Create an API key to use with 3rd party applications.'),
+    ];
   }
 
   return $form;
@@ -131,11 +134,12 @@ function shurly_api_key_form_submit($form, &$form_state) {
 
 /**
  * Implementation of hook_views_api.
- * Notifies the Views module that we're compatible with a particular API revision.
+ * Notifies the Views module that we're compatible with a particular API
+ * revision.
  */
 function shurly_service_views_api() {
-  return array(
+  return [
     'api' => 3,
     'path' => drupal_get_path('module', 'shurly_service') . '/views',
-  );
+  ];
 }
diff --git a/shurly_service/src/Controller/DefaultController.php b/shurly_service/src/Controller/DefaultController.php
index cc11e1a..cb6e614 100755
--- a/shurly_service/src/Controller/DefaultController.php
+++ b/shurly_service/src/Controller/DefaultController.php
@@ -15,14 +15,15 @@ class DefaultController extends ControllerBase {
       $api_validation = (is_numeric(shurly_get_uid($_REQUEST['apiKey']))) ? TRUE : FALSE;
     }
 
-    return \Drupal::currentUser()->hasPermission('Create short URLs') && $api_validation;
+    return \Drupal::currentUser()
+        ->hasPermission('Create short URLs') && $api_validation;
   }
 
   public function shurly_service_shorten() {
     $defaults = [
       'format' => 'json',
       // 'domain' => NULL,
-    'longUrl' => '',
+      'longUrl' => '',
       'shortUrl' => NULL,
       'apiKey' => NULL,
       'func' => 'urlData',
@@ -32,12 +33,14 @@ class DefaultController extends ControllerBase {
 
     module_load_include('inc', 'shurly_service', 'shurly_api_keys');
     $uid = isset($input['apiKey']) ? shurly_get_uid($input['apiKey']) : NULL;
-    $account = $uid ? \Drupal::entityTypeManager()->getStorage('user')->load($uid) : NULL;
+    $account = $uid ? \Drupal::entityTypeManager()
+      ->getStorage('user')
+      ->load($uid) : NULL;
     $access = $account->hasPermission('Create short URLs');
 
     if ($access) {
       // If the user doesn't have access to request a custom short URL from the
-    // service, reset it to NULL.
+      // service, reset it to NULL.
       if (!$account->hasPermission('Request custom short URL')) {
         $input['shortUrl'] = NULL;
       }
@@ -57,9 +60,9 @@ class DefaultController extends ControllerBase {
       'format' => 'json',
       // 'domain' => NULL,
       //'longUrl' => '',
-    'shortUrl' => '',
+      'shortUrl' => '',
       // 'login' => NULL,
-    'apiKey' => NULL,
+      'apiKey' => NULL,
       'func' => 'urlData',
       // function name for padded JSON
     ];
@@ -67,7 +70,9 @@ class DefaultController extends ControllerBase {
 
     module_load_include('inc', 'shurly_service', 'shurly_api_keys');
     $uid = isset($input['apiKey']) ? shurly_get_uid($input['apiKey']) : NULL;
-    $account = $uid ? \Drupal::entityTypeManager()->getStorage('user')->load($uid) : NULL;
+    $account = $uid ? \Drupal::entityTypeManager()
+      ->getStorage('user')
+      ->load($uid) : NULL;
     $access = $account->hasPermission('Expand short URLs');
 
     if ($access) {
diff --git a/shurly_service/views/shurly_service.views.inc b/shurly_service/views/shurly_service.views.inc
index 6b584f0..b8a8539 100755
--- a/shurly_service/views/shurly_service.views.inc
+++ b/shurly_service/views/shurly_service.views.inc
@@ -5,62 +5,62 @@
  */
 
 function shurly_service_views_data() {
-  
+
   // Basic table information.
-  $data['shurly_keys']['table']['group']  = t('Shurly Service');
+  $data['shurly_keys']['table']['group'] = t('Shurly Service');
 
   // Create a join association with the shurly table
-  $data['shurly_keys']['table']['join'] = array(
-    'shurly' => array(
+  $data['shurly_keys']['table']['join'] = [
+    'shurly' => [
       'left_field' => 'uid',
-      'field'      => 'uid',
-      )
-  );
+      'field' => 'uid',
+    ],
+  ];
 
   // UID 
-  $data['shurly_keys']['uid'] = array(
+  $data['shurly_keys']['uid'] = [
     'title' => t('User ID'),
     'help' => t('ID of user associated with the Shurly API Key.'),
-    'field' => array(
+    'field' => [
       'handler' => 'views_handler_field_user',
       'click sortable' => TRUE,
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'handler' => 'views_handler_argument_user_uid',
       'name field' => 'name', // display this field in the summary
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'title' => t('Name'),
       'handler' => 'views_handler_filter_user_name',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'handler' => 'views_handler_sort',
-    ),
-    'relationship' => array(
+    ],
+    'relationship' => [
       'handler' => 'views_handler_relationship',
       'base' => 'users',
       'base field' => 'uid',
       'label' => t('user'),
-    ),
-  );
+    ],
+  ];
 
   // API Key
-  $data['shurly_keys']['apikey'] = array(
+  $data['shurly_keys']['apikey'] = [
     'title' => t('API Key'),
     'help' => t('The API key associated with the user.'),
-    'field' => array(
+    'field' => [
       'handler' => 'views_handler_field',
-    ),
-    'filter' => array(
+    ],
+    'filter' => [
       'handler' => 'views_handler_filter_string',
-    ),
-    'sort' => array(
+    ],
+    'sort' => [
       'handler' => 'views_handler_sort',
-    ),
-    'argument' => array(
+    ],
+    'argument' => [
       'handler' => 'views_handler_argument_string',
-    ),
-  );
+    ],
+  ];
 
   return $data;
 
diff --git a/src/Form/ShurlyCreateForm.php b/src/Form/ShurlyCreateForm.php
index b5b2ba2..5334cf4 100755
--- a/src/Form/ShurlyCreateForm.php
+++ b/src/Form/ShurlyCreateForm.php
@@ -26,47 +26,49 @@ class ShurlyCreateForm extends FormBase {
    * {@inheritdoc}
    */
   public function buildForm(array $form, FormStateInterface $form_state) {
-    global $base_url;
-
     $form['#theme'] = 'shurly_create_form';
 
     $storage = &$form_state->getStorage();
 
-    $form['long_url'] = array(
+    $form['long_url'] = [
       '#type' => 'textfield',
       '#maxlength' => 2048,
       '#default_value' => isset($storage['shurly']['long_url']) ? $storage['shurly']['long_url'] : FALSE,
-      '#attributes' => array('tabindex' => 1, 'placeholder' => t('Enter a long URL to make short')),
-    );
+      '#attributes' => [
+        'tabindex' => 1,
+        'placeholder' => t('Enter a long URL to make short'),
+      ],
+    ];
 
-    $short_default = \Drupal::currentUser()->hasPermission('Enter custom URLs') ? (isset($storage['shurly']['short_url']) ? $storage['shurly']['short_url'] : '') : '';
+    $short_default = \Drupal::currentUser()
+      ->hasPermission('Enter custom URLs') ? (isset($storage['shurly']['short_url']) ? $storage['shurly']['short_url'] : '') : '';
 
-    $form['short_url'] = array(
-        '#type' => 'textfield',
-        '#size' => 6,
-        '#field_prefix' => \Drupal::config('shurly.settings')->get('shurly_base') . '/',
-        '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>',
-        '#default_value' => $short_default,
-        '#access' => \Drupal::currentUser()->hasPermission('Enter custom URLs'),
-        '#attributes' => array('tabindex' => 2),
-      );
+    $form['short_url'] = [
+      '#type' => 'textfield',
+      '#size' => 6,
+      '#field_prefix' => _shurly_get_shurly_base() . '/',
+      '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>',
+      '#default_value' => $short_default,
+      '#access' => \Drupal::currentUser()->hasPermission('Enter custom URLs'),
+      '#attributes' => ['tabindex' => 2],
+    ];
 
     if (isset($storage['shurly']['final_url'])) {
-      $form['result'] = array(
+      $form['result'] = [
         '#type' => 'textfield',
         '#size' => 30,
         '#value' => $storage['shurly']['final_url'],
         '#field_prefix' => t('Your short URL:'),
         '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div>
         <div class="social"><a href="http://twitter.com?status=' . urlencode($storage['shurly']['final_url']) . '">' . t('Create a Twitter message with this URL') . '</a></div>',
-      );
+      ];
     }
 
-    $form['submit'] = array(
+    $form['submit'] = [
       '#type' => 'submit',
       '#value' => t('Shrink it!'),
-      '#attributes' => array('tabindex' => 3),
-    );
+      '#attributes' => ['tabindex' => 3],
+    ];
 
     unset($storage['shurly']);
 
@@ -81,7 +83,10 @@ class ShurlyCreateForm extends FormBase {
 
     $rate_limit = shurly_rate_limit_allowed();
     if (!$rate_limit['allowed']) {
-      $form_state->setError('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])));
+      $form_state->setError('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', [
+        '@rate' => $rate_limit['rate'],
+        '@time' => $rate_limit['time'],
+      ]));
       return;
     }
 
@@ -100,18 +105,21 @@ class ShurlyCreateForm extends FormBase {
 
     if (trim($vals['short_url']) != '') {
       // a custom short URL has been entered
-      $form_state->setValue('custom', array(TRUE));
+      $form_state->setValue('custom', [TRUE]);
 
-    if (!shurly_validate_custom($vals['short_url'])) {
-      $form_state->setErrorByName('short_url', t('Short URL contains unallowed characters'));
-    }
-    elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) {
-      $form_state->setErrorByName('short_url', t('This short URL has already been used'));
+      if (!shurly_validate_custom($vals['short_url'])) {
+        $form_state->setErrorByName('short_url', t('Short URL contains unallowed characters'));
+      }
+      elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) {
+        $form_state->setErrorByName('short_url', t('This short URL has already been used'));
       }
-      elseif (_surl($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url'] || _surl($vals['short_url'], array('absolute' => TRUE, 'base_url' => \Drupal::config('shurly.settings')->get('shurly_base'))) == $vals['long_url']) {
+      elseif (_surl($vals['short_url'], ['absolute' => TRUE]) == $vals['long_url'] || _surl($vals['short_url'], [
+          'absolute' => TRUE,
+          'base_url' => _shurly_get_shurly_base(),
+        ]) == $vals['long_url']) {
         // check that link isn't to itself (creating infinite loop)
         // problem - http vs https
-        $form_state->setError('short_url', t('You cannot create links to themselves'));
+        $form_state->setErrorByName('short_url', t('You cannot create links to themselves'));
       }
       elseif (!shurly_path_available($vals['short_url'])) {
         $form_state->setErrorByName('short_url', t('This custom URL is reserved. Please choose another.'));
@@ -129,13 +137,13 @@ class ShurlyCreateForm extends FormBase {
         $short = shurly_next_url();
       }
       $form_state->setValue('short_url', $short);
-      $form_state->setStorage(array('shurly' => array('short_url' => $short)));
+      $form_state->setStorage(['shurly' => ['short_url' => $short]]);
     }
 
     // check that the destination URL is "safe"
-    if(\Drupal::config('shurly.settings')->get('shurly_gsb')){
+    if (\Drupal::config('shurly.settings')->get('shurly_gsb')) {
 
-     $gsb = shurly_gsb($vals['long_url']);
+      $gsb = shurly_gsb($vals['long_url']);
 
       if ($gsb) {
         $form_state->setErrorByName('long_url', t('This URL is either phishing, malware, or both.'));
@@ -153,14 +161,15 @@ class ShurlyCreateForm extends FormBase {
     $long_url = $form_state->getValue('long_url');
     $short_url = $form_state->getValue('short_url');
 
-    $form_state->setStorage(array('shurly' => array(
-      'long_url' => $long_url,
-      'short_url' => $short_url,
-      'final_url' => urldecode(\Drupal::config('shurly.settings')->get('shurly_base') . '/' . $short_url)
-      )
-    ));
-    
-    $custom = $form_state->setValue('custom', array($form_state->getValue('custom')));
+    $form_state->setStorage([
+      'shurly' => [
+        'long_url' => $long_url,
+        'short_url' => $short_url,
+        'final_url' => urldecode(_shurly_get_shurly_base() . '/' . $short_url),
+      ],
+    ]);
+
+    $custom = $form_state->setValue('custom', [$form_state->getValue('custom')]);
 
     $form_state->setRebuild();
 
diff --git a/src/Form/ShurlyDeactivateForm.php b/src/Form/ShurlyDeactivateForm.php
index ef52d78..3cfe93c 100755
--- a/src/Form/ShurlyDeactivateForm.php
+++ b/src/Form/ShurlyDeactivateForm.php
@@ -25,7 +25,9 @@ class ShurlyDeactivateForm extends ConfirmFormBase {
    */
   public function access(AccountInterface $account, $rid) {
     if (is_numeric($rid)) {
-      $row = \Drupal::database()->query('SELECT uid, source, destination FROM {shurly} WHERE rid = :rid', array('rid' => $rid))->fetchObject();
+      $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('deactivate own URLs') && $row->uid == $account->id());
     }
diff --git a/src/Form/ShurlyEditForm.php b/src/Form/ShurlyEditForm.php
index 97b3196..2c7e9f2 100755
--- a/src/Form/ShurlyEditForm.php
+++ b/src/Form/ShurlyEditForm.php
@@ -19,7 +19,7 @@ use Drupal\Core\Form\FormStateInterface;
  * ShurlyActionsForm.
  */
 class ShurlyEditForm extends FormBase {
-  
+
   /**
    * Access check for editing a short url.
    *
@@ -28,7 +28,9 @@ class ShurlyEditForm extends FormBase {
    */
   public function access(AccountInterface $account, $rid) {
     if (is_numeric($rid)) {
-      $row = \Drupal::database()->query('SELECT uid, source, destination FROM {shurly} WHERE rid = :rid', array('rid' => $rid))->fetchObject();
+      $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());
     }
@@ -45,83 +47,89 @@ class ShurlyEditForm extends FormBase {
    * {@inheritdoc}
    */
   public function buildForm(array $form, FormStateInterface $form_state, $rid = NULL) {
-    $shurly_link = \Drupal::database()->query('SELECT * FROM {shurly} WHERE rid = :rid', array('rid' => $rid))->fetchAllAssoc('rid');
-    $shurly_history = \Drupal::database()->query('SELECT * FROM {shurly_history} WHERE rid = :rid', array('rid' => $rid))->fetchAll();
+    $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(array('shurly' => array(
-      'rid' => $rid,
-      'source' => $shurly_link[$rid]->source,
-      'count' => $shurly_link[$rid]->count,
-      'destination' => urldecode($shurly_link[$rid]->destination)
-      )
-    ));
-
-    if($shurly_history){
-      $form['history'] = array(
+    $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'] = array(
-      '#markup' => '<thead>
+      $form['history']['header'] = [
+        '#markup' => '<thead>
         <tr>
-          <th>'.t('Source').'</th>
-          <th>'.t('Changed').'</th>
+          <th>' . t('Source') . '</th>
+          <th>' . t('Changed') . '</th>
         </tr>
       </thead>',
-      );
+      ];
 
-      for ($i=0; $i<$shurly_history_count; $i++) {
-        $form['history']['row_' . $i] = array(
-          '#prefix' => '<tr class="'.($i % 2 ? "odd" : "even").'">',
+      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'] = array(
-         '#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]['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'] = array(
+        $form['history']['row_' . $i]['last_date'] = [
           '#prefix' => '<td>',
           '#suffix' => '</td>',
           '#markup' => format_date($shurly_history[$i]->last_date, 'short'),
-        );
+        ];
       }
     }
 
-    $form['source'] = array(
+    $form['source'] = [
       '#type' => 'textfield',
       '#title' => 'source',
       '#value' => $shurly_link[$rid]->source,
       '#disabled' => TRUE,
-    );
+    ];
 
-    $form['destination'] = array(
+    $form['destination'] = [
       '#type' => 'textfield',
       '#title' => 'destination',
       '#value' => $shurly_link[$rid]->destination,
-    );
+    ];
 
-    $form['rid'] = array(
+    $form['rid'] = [
       '#type' => 'hidden',
       '#value' => $rid,
-    );
+    ];
 
-    $form['count'] = array(
+    $form['count'] = [
       '#type' => 'hidden',
       '#value' => $shurly_link[$rid]->count,
-    );
+    ];
 
-    $form['submit'] = array(
+    $form['submit'] = [
       '#type' => 'submit',
       '#value' => 'Submit',
-    );
+    ];
 
     return $form;
   }
@@ -147,25 +155,29 @@ class ShurlyEditForm extends FormBase {
     $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', array('rid' => $rid))->fetchAssoc();
+    $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)', array(
-      ':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'],
-    ));
+    \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', array(
-      ':new_destination' => $new_destination,
-      ':reset_count' => 0,
-      'rid' => $rid
-    ));
+    \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']);
 
diff --git a/src/Form/ShurlySettingsForm.php b/src/Form/ShurlySettingsForm.php
index c7915fa..e3b898b 100755
--- a/src/Form/ShurlySettingsForm.php
+++ b/src/Form/ShurlySettingsForm.php
@@ -15,20 +15,21 @@ use Drupal\Core\Form\ConfigFormBase;
  * ShurlySettingsForm.
  */
 class ShurlySettingsForm extends ConfigFormBase {
+
   /**
    * {@inheritdoc}
    */
-   public function __construct(ConfigFactoryInterface $config_factory) {
-     parent::__construct($config_factory);
-   }
+  public function __construct(ConfigFactoryInterface $config_factory) {
+    parent::__construct($config_factory);
+  }
 
   /**
    * {@inheritdoc}
    */
   protected function getEditableConfigNames() {
-    return array(
+    return [
       'shurly.settings',
-    );
+    ];
   }
 
   /**
@@ -42,152 +43,154 @@ class ShurlySettingsForm extends ConfigFormBase {
    * {@inheritdoc}
    */
   public function buildForm(array $form, FormStateInterface $form_state) {
-    global $base_url;
-
     $config = $this->config('shurly.settings');
 
-    $form['shurly_url'] = array(
+    $form['shurly_url'] = [
       '#type' => 'fieldset',
       '#title' => t('Base URL'),
-      '#description' => t('If you want to use a dedicated url for the short URL\'s, enter below that short base URL to be used.'),
-    );
+      '#description' => t('If you want to use a dedicated url for the short URL\'s, enter above that short base URL to be used.'),
+    ];
 
-    $form['shurly_url']['shurly_base'] = array(
+    $form['shurly_url']['shurly_base'] = [
       '#type' => 'textfield',
-      '#description' => t('Default is the base URL of the Drupal installation.'),
+      '#description' => t('Leave empty to use the default base URL of the Drupal installation'),
       '#default_value' => $config->get('shurly_base'),
-      '#required' => TRUE,
-    );
+      '#required' => FALSE,
+    ];
 
-    $form['shurly_redirect'] = array(
+    $form['shurly_redirect'] = [
       '#type' => 'fieldset',
       '#title' => t('Redirect URL'),
       '#description' => t('Define the redirect page when the short link is deactivated.'),
-    );
+    ];
 
-    $form['shurly_redirect']['shurly_redirect_page'] = array(
+    $form['shurly_redirect']['shurly_redirect_page'] = [
       '#type' => 'textfield',
-      '#field_prefix' => $base_url . '/',
+      '#field_prefix' => _shurly_get_shurly_base() . '/',
       '#description' => t('Page displayed when the link is deactivated. If not defined, the default 404 page will be used.'),
       '#default_value' => $config->get('shurly_redirect_page'),
-    );
+    ];
 
-    $form['shurly_restrictions'] = array(
+    $form['shurly_restrictions'] = [
       '#type' => 'fieldset',
       '#title' => t('Restrictions'),
       '#description' => t('Restrict short URL targets. Be aware of the fact, that the localhost, local network and unresolvable restriction are resolving the given address by staging a DNS request, which can significantly <strong>slow down the short URL creation</strong>!'),
-    );
+    ];
 
-    $form['shurly_restrictions']['shurly_forbid_localhost'] = array(
+    $form['shurly_restrictions']['shurly_forbid_localhost'] = [
       '#type' => 'checkbox',
       '#title' => t('Forbid localhost'),
       '#description' => t('Do not allow creation of short URLs targeting localhost addresses.'),
       '#default_value' => $config->get('shurly_forbid_localhost'),
-    );
+    ];
 
-    $form['shurly_restrictions']['shurly_forbid_private_ips'] = array(
+    $form['shurly_restrictions']['shurly_forbid_private_ips'] = [
       '#type' => 'checkbox',
       '#title' => t('Forbid private IP ranges'),
       '#description' => t('Do not allow creation of short URLs targeting private IP ranges.'),
       '#default_value' => $config->get('shurly_forbid_private_ips'),
-    );
+    ];
 
-    $form['shurly_restrictions']['shurly_forbid_unresolvable_hosts'] = array(
+    $form['shurly_restrictions']['shurly_forbid_unresolvable_hosts'] = [
       '#type' => 'checkbox',
       '#title' => t('Forbid unresolvable hostnames'),
       '#description' => t('Do not allow creation of short URLs targeting host addresses that cannot be resolved.'),
       '#default_value' => $config->get('shurly_forbid_unresolvable_hosts'),
-    );
+    ];
 
-    $form['shurly_restrictions']['shurly_forbid_ips'] = array(
+    $form['shurly_restrictions']['shurly_forbid_ips'] = [
       '#type' => 'checkbox',
       '#title' => t('Forbid direct IP redirects'),
       '#description' => t('Do not allow creation of short URLs containing an IP address instead of a human readable hostname.'),
       '#default_value' => $config->get('shurly_forbid_ips'),
-    );
+    ];
 
-    $form['shurly_restrictions']['shurly_forbid_custom'] = array(
+    $form['shurly_restrictions']['shurly_forbid_custom'] = [
       '#type' => 'checkbox',
       '#title' => t('Forbid URL target by custom pattern'),
       '#description' => t('Define a custom pattern (RegEx) to forbid some kind of target URLs.'),
       '#default_value' => $config->get('shurly_forbid_custom'),
-      '#attributes' => array(
+      '#attributes' => [
         'onchange' => "jQuery('#shurly_custom_restriction_container').toggle();",
-      ),
-    );
+      ],
+    ];
 
-    $form['shurly_restrictions']['shurly_custom_restriction'] = array(
+    $form['shurly_restrictions']['shurly_custom_restriction'] = [
       '#type' => 'textfield',
       '#title' => t('Custom pattern'),
       '#description' => t('PERL regular expression defining a forbidden URL pattern.'),
       '#default_value' => $config->get('shurly_custom_restriction'),
-    );
+    ];
 
-    $form['shurly_restrictions']['shurly_gsb'] = array(
+    $form['shurly_restrictions']['shurly_gsb'] = [
       '#type' => 'checkbox',
       '#title' => t('Google Safe Browsing'),
       '#description' => t('Check if a long URL is blacklisted against Google Safe Browsing. This service
         requires a Google developer account and is limited to 10,000 queries per day.'),
       '#default_value' => $config->get('shurly_gsb'),
-      '#attributes' => array(
+      '#attributes' => [
         'onchange' => "jQuery('.shurly_gsb_container').toggle();",
-      ),
-    );
+      ],
+    ];
 
-    $form['shurly_restrictions']['shurly_gsb_client'] = array(
+    $form['shurly_restrictions']['shurly_gsb_client'] = [
       '#type' => 'textfield',
       '#title' => t('Client'),
       '#description' => t('You can choose any name. Google suggests that you choose a name that represents the true identiy
          of the client (ie: name of your company).'),
       '#default_value' => $config->get('shurly_gsb_client'),
-    );
+    ];
 
-    $form['shurly_restrictions']['shurly_gsb_apikey'] = array(
+    $form['shurly_restrictions']['shurly_gsb_apikey'] = [
       '#type' => 'textfield',
       '#title' => t('API Key'),
       '#description' => t('Add your API key.'),
       '#default_value' => $config->get('shurly_gsb_apikey'),
-    );
+    ];
 
-    $form['shurly_throttle'] = array(
+    $form['shurly_throttle'] = [
       '#type' => 'fieldset',
       '#title' => t('Rate limiting'),
       '#tree' => TRUE,
       '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here.'),
-    );
+    ];
 
     $saved = $config->get('shurly_throttle');
 
-    foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) {
+    /**
+     * @var string $rid
+     * @var \Drupal\user\Entity\Role $role
+     */
+    foreach (user_roles(FALSE, 'Create short URLs') as $rid => $role) {
       $rate = isset($saved[$rid]['rate']) ? $saved[$rid]['rate'] : NULL;
       $time = isset($saved[$rid]['time']) ? $saved[$rid]['time'] : NULL;
 
-      $form['shurly_throttle'][$rid] = array(
+      $form['shurly_throttle'][$rid] = [
         '#type' => 'fieldset',
-        '#title' => $rid->name,
+        '#title' => $role->label(),
         '#tree' => TRUE,
-      );
-      $form['shurly_throttle'][$rid]['rate'] = array(
+      ];
+      $form['shurly_throttle'][$rid]['rate'] = [
         '#type' => 'textfield',
         '#size' => '3',
         '#prefix' => '<div class="container-inline">',
         '#field_suffix' => ' ' . t('requests'),
         '#default_value' => $rate,
-      );
-      $form['shurly_throttle'][$rid]['time'] = array(
+      ];
+      $form['shurly_throttle'][$rid]['time'] = [
         '#type' => 'textfield',
         '#size' => '3',
         '#field_prefix' => t('within'),
         '#field_suffix' => ' ' . t('minutes'),
         '#default_value' => $time,
         '#suffix' => '</div>',
-      );
-      $form['shurly_throttle'][$rid]['weight'] = array(
+      ];
+      $form['shurly_throttle'][$rid]['weight'] = [
         '#type' => 'weight',
         '#title' => t('Weight'),
         '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0,
         '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'),
-      );
+      ];
 
     }
 
@@ -198,8 +201,9 @@ class ShurlySettingsForm extends ConfigFormBase {
    * {@inheritdoc}
    */
   public function validateForm(array &$form, FormStateInterface $form_state) {
-    $custom_base_url = $form_state->getValue('shurly_base');
-    if(!UrlHelper::isValid($custom_base_url, $absolute = TRUE)){
+    $custom_base_url = trim($form_state->getValue('shurly_base'));
+    // We need to deal with an empty value here. But then wie don't need to validate the url.
+    if (!empty($custom_base_url) && !UrlHelper::isValid($custom_base_url, $absolute = TRUE)) {
       $form_state->setErrorByName('shurly_base', t('The base URL is not valid.'));
     }
   }
@@ -207,12 +211,12 @@ class ShurlySettingsForm extends ConfigFormBase {
   /**
    * {@inheritdoc}
    */
-   public function submitForm(array &$form, FormStateInterface $form_state) {
+  public function submitForm(array &$form, FormStateInterface $form_state) {
     $config = $this->config('shurly.settings');
     $form_state->cleanValues();
 
     foreach ($form_state->getValues() as $key => $value) {
-      if(!empty($value) && !is_array($value)){
+      if (!empty($value) && !is_array($value)) {
         $config->set($key, $value);
       }
     }
diff --git a/src/Plugin/Block/ShurlyBlock.php b/src/Plugin/Block/ShurlyBlock.php
index a51f8be..8cdfe9f 100755
--- a/src/Plugin/Block/ShurlyBlock.php
+++ b/src/Plugin/Block/ShurlyBlock.php
@@ -25,17 +25,18 @@ class ShurlyBlock extends BlockBase {
   protected function blockAccess(AccountInterface $account) {
     $current_path = \Drupal::service('path.current')->getPath();
     $path_args = explode('/', $current_path);
-    
-    if ($account->hasPermission('create short URLs') && $path_args[0] != 'shurly'){
-      return True;
+
+    if ($account->hasPermission('create short URLs') && $path_args[0] != 'shurly') {
+      return TRUE;
     }
   }
-  
+
   /**
    * {@inheritdoc}
    */
   public function build() {
-    $form = \Drupal::formBuilder()->getForm('Drupal\shurly\Form\ShurlyCreateForm');
+    $form = \Drupal::formBuilder()
+      ->getForm('Drupal\shurly\Form\ShurlyCreateForm');
 
     return $form;
   }
diff --git a/src/Plugin/Filter/ShurlyFilter.php b/src/Plugin/Filter/ShurlyFilter.php
index 4f6483f..dd3799b 100755
--- a/src/Plugin/Filter/ShurlyFilter.php
+++ b/src/Plugin/Filter/ShurlyFilter.php
@@ -9,22 +9,24 @@ use Drupal\filter\Plugin\FilterBase;
  * @Filter(
  *   id = "shurly_filter",
  *   title = @Translation("Shorten all outgoing URL's"),
- *   description = @Translation("All links starting with http or https will be replaced."),
- *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE
+ *   description = @Translation("All links starting with http or https will be
+ *   replaced."), type =
+ *   Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE
  * )
  */
 class ShurlyFilter extends FilterBase {
+
   public function process($text, $langcode) {
-	  preg_match_all('/<a[^>]*href="(http[^"]*)"[^>]*>/i', $text, $links);
-	  if (!empty($links)) {
-	    $links = $links[1];
-	    foreach ($links as $key => $link) {
-	      $short_url = shurly_shorten($link);
-	      if ($short_url['success'] === TRUE) {
-	        $text = str_replace('"' . $link . '"', '"' . $short_url['shortUrl'] . '"', $text);
-	      }
-	    }
-	  }
-	  return new FilterProcessResult($text);
-	}
+    preg_match_all('/<a[^>]*href="(http[^"]*)"[^>]*>/i', $text, $links);
+    if (!empty($links)) {
+      $links = $links[1];
+      foreach ($links as $key => $link) {
+        $short_url = shurly_shorten($link);
+        if ($short_url['success'] === TRUE) {
+          $text = str_replace('"' . $link . '"', '"' . $short_url['shortUrl'] . '"', $text);
+        }
+      }
+    }
+    return new FilterProcessResult($text);
+  }
 }
diff --git a/src/Plugin/views/field/ShurlyLinkDeactivate.php b/src/Plugin/views/field/ShurlyLinkDeactivate.php
index f541d31..79d35f2 100755
--- a/src/Plugin/views/field/ShurlyLinkDeactivate.php
+++ b/src/Plugin/views/field/ShurlyLinkDeactivate.php
@@ -3,7 +3,7 @@
 namespace Drupal\shurly\Plugin\views\field;
 
 use Drupal\Core\Link;
-use Drupal\Core\Url; 
+use Drupal\Core\Url;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\views\Plugin\views\field\FieldPluginBase;
 use Drupal\views\ResultRow;
@@ -18,7 +18,7 @@ use Drupal\views\Plugin\views\display\DisplayPluginBase;
  * @ViewsField("shurly_link_deactivate")
  */
 class ShurlyLinkDeactivate extends FieldPluginBase {
-  
+
   /**
    * {@inheritdoc}
    */
@@ -32,18 +32,18 @@ class ShurlyLinkDeactivate extends FieldPluginBase {
 
   protected function defineOptions() {
     $options = parent::defineOptions();
-    
-    $options['text'] = array('default' => '', 'translatable' => TRUE);
-    
+
+    $options['text'] = ['default' => '', 'translatable' => TRUE];
+
     return $options;
   }
 
   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
-    $form['text'] = array(
+    $form['text'] = [
       '#type' => 'textfield',
       '#title' => t('Text to display'),
       '#default_value' => $this->options['text'],
-    );
+    ];
 
     parent::buildOptionsForm($form, $form_state);
   }
@@ -67,10 +67,15 @@ class ShurlyLinkDeactivate extends FieldPluginBase {
       return t('deactivated');
     }
     // only allow the user to view the link if they can actually delete
-    if (\Drupal::currentUser()->hasPermission('Administer short URLs') || (\Drupal::currentUser()->hasPermission('Deactivate own URLs') && $uid == $user->uid)) {
+    if (\Drupal::currentUser()
+        ->hasPermission('Administer short URLs') || (\Drupal::currentUser()
+          ->hasPermission('Deactivate own URLs') && $uid == $user->uid)) {
       $text = !empty($this->options['text']) ? $this->options['text'] : t('deactivate');
       $rid = $values->rid;
-      return link::fromTextAndUrl($text, Url::fromUri('internal:/shurly/deactivate/'.$rid, ['query' => \Drupal::service('redirect.destination')->getAsArray()]))->toString();
+      return link::fromTextAndUrl($text, Url::fromUri('internal:/shurly/deactivate/' . $rid, [
+        'query' => \Drupal::service('redirect.destination')
+          ->getAsArray(),
+      ]))->toString();
     }
   }
 }
diff --git a/src/Plugin/views/field/ShurlyLinkEdit.php b/src/Plugin/views/field/ShurlyLinkEdit.php
index a1ff9d5..07e9fa2 100755
--- a/src/Plugin/views/field/ShurlyLinkEdit.php
+++ b/src/Plugin/views/field/ShurlyLinkEdit.php
@@ -35,9 +35,9 @@ class ShurlyLinkEdit extends FieldPluginBase {
    */
   protected function defineOptions() {
     $options = parent::defineOptions();
-    
-    $options['text'] = array('default' => '', 'translatable' => TRUE);
-    
+
+    $options['text'] = ['default' => '', 'translatable' => TRUE];
+
     return $options;
   }
 
@@ -45,11 +45,11 @@ class ShurlyLinkEdit extends FieldPluginBase {
    * {@inheritdoc}
    */
   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
-    $form['text'] = array(
+    $form['text'] = [
       '#type' => 'textfield',
       '#title' => t('Text to display'),
       '#default_value' => $this->options['text'],
-    );
+    ];
 
     parent::buildOptionsForm($form, $form_state);
   }
@@ -73,10 +73,15 @@ class ShurlyLinkEdit extends FieldPluginBase {
       return t('deactivated');
     }
     // only allow the user to view the link if they can actually edit
-    if (\Drupal::currentUser()->hasPermission('Administer short URLs') || (\Drupal::currentUser()->hasPermission('Edit own URLs') && $uid == $user->uid)) {
+    if (\Drupal::currentUser()
+        ->hasPermission('Administer short URLs') || (\Drupal::currentUser()
+          ->hasPermission('Edit own URLs') && $uid == $user->uid)) {
       $text = !empty($this->options['text']) ? $this->options['text'] : t('edit');
       $rid = $this->getValue($values, 'rid');
-      return link::fromTextAndUrl($text, Url::fromUri('internal:/shurly/edit/'.$rid, ['query' => \Drupal::service('redirect.destination')->getAsArray()]))->toString();
+      return link::fromTextAndUrl($text, Url::fromUri('internal:/shurly/edit/' . $rid, [
+        'query' => \Drupal::service('redirect.destination')
+          ->getAsArray(),
+      ]))->toString();
     }
   }
 }
diff --git a/src/Plugin/views/field/ShurlyShortUrl.php b/src/Plugin/views/field/ShurlyShortUrl.php
index f47b5a5..d02e39a 100755
--- a/src/Plugin/views/field/ShurlyShortUrl.php
+++ b/src/Plugin/views/field/ShurlyShortUrl.php
@@ -29,9 +29,9 @@ class ShurlyShortUrl extends FieldPluginBase {
   protected function defineOptions() {
     $options = parent::defineOptions();
 
-    $options['text'] = array('default' => '', 'translatable' => TRUE);
-    $options['longshort'] = array('default' => 0, 'translatable' => FALSE);
-    $options['link'] = array('default' => FALSE, 'translatable' => FALSE);
+    $options['text'] = ['default' => '', 'translatable' => TRUE];
+    $options['longshort'] = ['default' => 0, 'translatable' => FALSE];
+    $options['link'] = ['default' => FALSE, 'translatable' => FALSE];
 
     return $options;
   }
@@ -41,26 +41,26 @@ class ShurlyShortUrl extends FieldPluginBase {
     unset($form['hide_empty']);
     unset($form['hide_empty']);
 
-    $form['text'] = array(
+    $form['text'] = [
       '#type' => 'textfield',
       '#title' => t('Text to display'),
       '#default_value' => $this->options['text'],
-    );
+    ];
 
-    $form['longshort'] = array(
+    $form['longshort'] = [
       '#type' => 'radios',
-      '#options' => array(
+      '#options' => [
         0 => t('Output full URL including base path'),
         1 => t('Output only the short path'),
-      ),
+      ],
       '#default_value' => $this->options['longshort'],
-    );
-    $form['link'] = array(
+    ];
+    $form['link'] = [
       '#type' => 'checkbox',
       '#title' => t('Output as link'),
       '#default_value' => $this->options['link'],
       '#description' => t('Wrap output with a link to the short URL. Use <em>Output this field as a link</em> above for more complex options.'),
-    );
+    ];
 
     parent::buildOptionsForm($form, $form_state);
   }
@@ -87,12 +87,12 @@ class ShurlyShortUrl extends FieldPluginBase {
         $text = $source;
       }
       else {
-        $text = rawurldecode(_surl($source, array('absolute' => TRUE)));
+        $text = rawurldecode(_surl($source, ['absolute' => TRUE]));
       }
     }
 
     if ($this->options['link']) {
-      $text = _sl($text, $source, array('attributes' => ['target' => ['_blank']]));
+      $text = _sl($text, $source, ['attributes' => ['target' => ['_blank']]]);
     }
 
     return $text;
diff --git a/src/ShurlySubscriber.php b/src/ShurlySubscriber.php
index d714194..de58155 100755
--- a/src/ShurlySubscriber.php
+++ b/src/ShurlySubscriber.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\shurly;
 
+use Drupal\Core\Url;
 use Symfony\Component\HttpFoundation\RedirectResponse;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpKernel\KernelEvents;
@@ -20,34 +21,39 @@ class ShurlySubscriber implements EventSubscriberInterface {
   }
 
   public function shurlyOnRespond(GetResponseEvent $event) {
-    global $base_url;
     $path = \Drupal::service('path.current')->getPath();
     $current_path = str_replace("/", "", $path);
 
-    if (shurly_validate_custom($current_path) && !empty($_GET['redirect'])){
-      $row = \Drupal::database()->query("SELECT rid, destination FROM {shurly} WHERE source = :q AND active = 1", [':q' => $current_path])->fetchObject();
+    if (shurly_validate_custom($current_path)) {
+      $row = \Drupal::database()
+        ->query("SELECT rid, destination, active FROM {shurly} WHERE source = :q ", [':q' => $current_path])
+        ->fetchObject();
+
       if ($row) {
-        $this->shurlyRedirectTo($row);
-      }
-      elseif (\Drupal::config('shurly.settings')->get('shurly_redirect_page')) {
-        $row = \Drupal::database()->query("SELECT rid, destination FROM {shurly} WHERE source = :q AND active = 0", [
-          ':q' => $_GET['q']
-          ])->fetchObject();
-        if ($row) {
-          $options = ['query' => ['d' => $row->destination],];
-          $row->destination = _surl(Drupal::config('shurly.settings')->get('shurly_redirect_page'), $options);
+        if ($row->active == 1) {
           $this->shurlyRedirectTo($row);
         }
+        else {
+          // Check if the redirect page is defined. Otherwise the request will
+          // be handled normally by drupal.
+          $shurly_redirect_url = trim(\Drupal::config('shurly.settings')->get('shurly_redirect_page'));
+          if (!empty($shurly_redirect_url)) {
+            $url = Url::fromUserInput($shurly_redirect_url);
+            $response = new RedirectResponse($url->toString());
+            $response->send();
+            return;
+          }
+        }
       }
     }
   }
 
-  protected function shurlyRedirectTo($row){
+  protected function shurlyRedirectTo($row) {
     \Drupal::moduleHandler()->invokeAll('shurly_redirect_before', [$row]);
 
     $url = $row->destination;
 
-    $url = str_replace(array("\n", "\r"), '', $url);
+    $url = str_replace(["\n", "\r"], '', $url);
 
     session_write_close();
 
@@ -56,7 +62,11 @@ class ShurlySubscriber implements EventSubscriberInterface {
 
     $request_time = \Drupal::time()->getRequestTime();
 
-    \Drupal::database()->query('UPDATE {shurly} SET count = count + 1, last_used = :time WHERE rid = :rid', ['time' => $request_time, 'rid' => $row->rid]);
+    \Drupal::database()
+      ->query('UPDATE {shurly} SET count = count + 1, last_used = :time WHERE rid = :rid', [
+        'time' => $request_time,
+        'rid' => $row->rid,
+      ]);
 
     \Drupal::moduleHandler()->invokeAll('shurly_redirect_after', [$row]);
 
diff --git a/templates/shurly-create-form.html.twig b/templates/shurly-create-form.html.twig
index 333f56c..27f1112 100755
--- a/templates/shurly-create-form.html.twig
+++ b/templates/shurly-create-form.html.twig
@@ -6,9 +6,9 @@
 {{ form.short_url }}
 
  {% if form.result %}
- 	<div class="shurly-result">
- 		{{ form.result }}
- 	</div>
+   <div class="shurly-result">
+     {{ form.result }}
+   </div>
  {% endif %}
 
 {{ form.submit }}
