Longman\TelegramBot\BotanDB::insertShortUrl PHP Method

insertShortUrl() public static method

Insert shortened URL into the database
public static insertShortUrl ( $user_id, $url, $short_url ) : boolean
$user_id
$url
$short_url
return boolean
    public static function insertShortUrl($user_id, $url, $short_url)
    {
        if (!self::isDbConnected()) {
            return false;
        }
        try {
            $sth = self::$pdo->prepare('INSERT INTO `' . TB_BOTAN_SHORTENER . '`
                (
                `user_id`, `url`, `short_url`, `created_at`
                )
                VALUES (
                :user_id, :url, :short_url, :date
                )
            ');
            $created_at = self::getTimestamp();
            $sth->bindParam(':user_id', $user_id);
            $sth->bindParam(':url', $url);
            $sth->bindParam(':short_url', $short_url);
            $sth->bindParam(':date', $created_at);
            return $sth->execute();
        } catch (Exception $e) {
            throw new TelegramException($e->getMessage());
        }
    }

Usage Example

Beispiel #1
0
 /**
  * Url Shortener function
  *
  * @param  $url
  * @param  $user_id
  *
  * @return string
  * @throws \Longman\TelegramBot\Exception\TelegramException
  */
 public static function shortenUrl($url, $user_id)
 {
     if (empty(self::$token)) {
         return $url;
     }
     if (empty($user_id)) {
         throw new TelegramException('User id is empty!');
     }
     $cached = BotanDB::selectShortUrl($user_id, $url);
     if (!empty($cached[0]['short_url'])) {
         return $cached[0]['short_url'];
     }
     $request = str_replace(['#TOKEN', '#UID', '#URL'], [self::$token, $user_id, urlencode($url)], self::$shortener_url);
     $options = ['http' => ['ignore_errors' => true, 'timeout' => 3]];
     $context = stream_context_create($options);
     $response = @file_get_contents($request, false, $context);
     if (!filter_var($response, FILTER_VALIDATE_URL) === false) {
         BotanDB::insertShortUrl($user_id, $url, $response);
     } else {
         TelegramLog::debug('Botan.io API replied with error: ' . $response);
         return $url;
     }
     return $response;
 }