/** * @param string $uri * @return StreamInterface */ public static function getUriBody($uri) { if (!Validation::isValidLink($uri)) { throw new InvalidUriException($uri . ' is not a valid link'); } $httpClient = new Client(); $resource = $httpClient->get($uri, ['allow_redirects' => true, 'connect_timeout' => 2, 'timeout' => 5]); unset($httpClient); $contents = $resource->getBody(); unset($resource); return $contents; }
/** * @param string $string * @return string */ public static function extractUriFromString($string) { if (empty($string)) { throw new NoUriFoundException(); } $hasMatches = preg_match('/https?\\:\\/\\/[A-Za-z0-9\\-\\/._~:?#@!$&\'()*+,;=%]+/i', $string, $matches); if (!$hasMatches || empty($matches)) { throw new NoUriFoundException(); } $possibleUri = $matches[0]; if (!Validation::isValidLink($possibleUri)) { throw new NoUriFoundException(); } return $possibleUri; }
/** * @param string $uri * @return string */ public static function createShortLink($uri) { if (!Validation::isValidLink($uri)) { throw new InvalidUriException($uri . ' is not a valid link'); } // Pieces... $shortenerBaseUrl = 'http://is.gd/create.php?format=json&url=%s'; $uri = urlencode($uri); // Add them together... $shortenerUrl = sprintf($shortenerBaseUrl, $uri); // And fire a request. $body = Remote::getUriBody($shortenerUrl); $contents = $body->getContents(); if (!($decoded = json_decode($contents)) || empty($decoded->shorturl)) { throw new ShortUriCreationFailedException('Received an invalid result set'); } return $decoded->shorturl; }