Example #1
0
 /**
  * Generates a shortened string for a given $target url and stores it inside the database.
  *
  * The generated string (here $short) follows several rules:
  *
  * - if strlen($target) > 4 then strlen($target) > strlen($short) else strlen($short) = 4
  *
  * - $target !== $short
  *
  * - length of $short is 4
  *
  * - $short contains only numbers and capitalised consonants.
  *
  * The function assumes that the $target url exists. Aim of the function is
  * to generate a string that is similar to the target url.
  * The return value is of type ShortURL which holds
  * several information about the generated URL.
  *
  * @param string $url
  *            the target
  * @return ShortURL
  */
 public function generateShortURL($target)
 {
     $newTarget = preg_replace('/[aeiou,.\\/\\\\-_&=:\\s]+/i', '', $target);
     $newTarget = strtoupper($newTarget);
     $newTarget = str_shuffle($newTarget);
     /*
      * If string has more than 4 character pick the first 4 character.
      * else if string has less than 4 character fill missing character.
      */
     if (strlen($newTarget) > 4) {
         $newTarget = substr($newTarget, 0, 4);
     } else {
         if (strlen($newTarget) < 4) {
             $newTarget = $newTarget . $this->generateRandomString(4 - strlen($newTarget));
         }
     }
     if ($this->exists($newTarget)) {
         $newTarget = $this->randomizer($newTarget);
     }
     $short = new ShortURL($this->config['shortener']['targetURL']);
     $short->setTarget($target);
     $short->setShortName($newTarget);
     $short->setDateCreated(time());
     $short->setDateExpire($short->getDateCreated() + 4 * 24 * 60 * 60);
     $this->dbManager->insertShortURL($short);
     return $short;
 }
Example #2
0
 /**
  * Inserts a ShortURL into the database.
  *
  * @param \ShortURL $url
  *            the ShortURL that needs be stored inside the database.
  * @return \\ShortURL which is updated by this method.
  */
 public function insertShortURL(\ShortURL $url)
 {
     $con = $this->getConnection();
     if (isset($con)) {
         $query = "INSERT INTO shortener (id, shortName, target, dateCreated, dateExpired) \n                VALUES (null, :shortName, :target, :dateCreated, :dateExpired)";
         $stmt = $con->prepare($query);
         $stmt->bindParam(':shortName', $url->getShortName());
         $stmt->bindParam(':target', $url->getTarget());
         $stmt->bindParam(':dateCreated', $url->getDateCreated());
         $stmt->bindParam(':dateExpired', $url->getDateExpire());
         $stmt->execute();
         $id = $con->lastInsertId();
         $url->setId($id);
         return $url;
     }
 }