Skip to content

Commit

Permalink
Merge pull request open-runtimes#36 from TheSylwio/generate-short-url
Browse files Browse the repository at this point in the history
⚡ Write a generateShortUrl() Function using PHP
  • Loading branch information
Meldiron committed Jan 22, 2023
2 parents 71971c2 + 6d6453e commit 7d60268
Show file tree
Hide file tree
Showing 2 changed files with 171 additions and 0 deletions.
94 changes: 94 additions & 0 deletions php/generate-short-url/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Generate short URL

A PHP Cloud Function that for URL shortener service name and URL returns shorten link.

Available services:

* [Bitly](https://bitly.com)
* [Tinyurl](https://tinyurl.com/)

_Example input:_

```json
{
"provider": "bitly",
"url": "https://appwrite.io/"
}
```

```json
{
"provider": "tinyurl",
"url": "https://facebook.com/"
}
```

_Example output:_

```json
{
"success": true,
"url": "https://bit.ly/3SDBqnK"
}
```

```json
{
"success": true,
"url": "https://tinyurl.com/47ksc2ud"
}
```

```json
{
"success": false,
"message": "Provided unsupported provider name. [bitly, tinyurl]"
}
```

## 📝 Environment Variables

List of environment variables used by this cloud function:

- **API_BITLY_AUTHORIZATION_TOKEN** - Bitly authorization token
- **API_TINYURL_AUTHORIZATION_TOKEN** - Tinyurl authorization token

## 🚀 Deployment

1. Clone this repository, and enter this function folder:

```
$ git clone https://github.com/open-runtimes/examples.git && cd examples
$ cd php/generate-short-url
```

2. Enter this function folder and build the code:

```
docker run --rm --interactive --tty --volume $PWD:/usr/code openruntimes/php:v2-8.1 sh /usr/local/src/build.sh
```

As a result, a `code.tar.gz` file will be generated.

3. Start the Open Runtime:

```
docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key -e INTERNAL_RUNTIME_ENTRYPOINT=index.php --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/php:v2-8.1 sh /usr/local/src/start.sh
```

Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate
authorization headers. To learn more about runtime, you can visit PHP
runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/php-8.1).

4. Execute function:

```
curl http:https://localhost:3000/ -d '{"variables":{"API_BITLY_AUTHORIZATION_TOKEN":"[YOUR_API_KEY]"},"payload": "{\"url\":\"https://appwrite.io/\",\"provider\":\"bitly\"}"}' -H "X-Internal-Challenge: secret-key" -H "Content-Type: application/json"
```

## 📝 Notes

- This function is designed for use with Appwrite Cloud Functions. You can learn more about it
in [Appwrite docs](https://appwrite.io/docs/functions).
- This example is compatible with PHP 8.1. Other versions may work but are not guaranteed to work as they haven't been
tested.
77 changes: 77 additions & 0 deletions php/generate-short-url/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

return function ($req, $res) {
$payload = json_decode($req['payload'] ?? '{}', true);

$chosenProvider = $payload['provider'] ?? null;
$longUrl = $payload['url'] ?? null;

if (null === $chosenProvider) {
$res->json(['success' => false, 'message' => 'Provider param is required. [bitly, tinyurl]'], 400);
return;
}

if (false === in_array($chosenProvider, ['bitly', 'tinyurl'])) {
$res->json(['success' => false, 'message' => 'Provided unsupported provider name. [bitly, tinyurl]'], 400);
return;
}

// Prepare request data
switch ($chosenProvider) {
case 'bitly':
$apiUrl = 'https://api-ssl.bitly.com/v4/shorten';
$authorizationToken = $req['variables']['API_BITLY_AUTHORIZATION_TOKEN'] ?? null;
$data = json_encode(['long_url' => $longUrl]);
break;
case 'tinyurl':
$apiUrl = 'https://api.tinyurl.com/create';
$authorizationToken = $req['variables']['API_TINYURL_AUTHORIZATION_TOKEN'] ?? null;
$data = json_encode(['url' => $longUrl]);
break;
default:
$apiUrl = null;
$authorizationToken = null;
$data = null;
}

if (null === $authorizationToken) {
$res->json(['success' => false, 'message' => 'Authorization token not set in variables'], 401);
return;
}

// Make request
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $apiUrl);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
sprintf('Authorization: Bearer %s', $authorizationToken)
]);

$apiResponse = json_decode(curl_exec($curl), true);
curl_close($curl);

// Extract request result
switch ($chosenProvider) {
case 'bitly':
$shortenUrl = $apiResponse['link'] ?? null;
$errorMessage = $apiResponse['message'] ?? null;
break;
case 'tinyurl':
$shortenUrl = $apiResponse['data']['tiny_url'] ?? null;
$errorMessage = $apiResponse['errors'][0] ?? null;
break;
default:
$shortenUrl = null;
$errorMessage = 'Error.';
}

if (null === $shortenUrl) {
$res->json(['success' => false, 'message' => $errorMessage], 401);
return;
}

$res->json(['success' => true, 'url' => $shortenUrl]);
};

0 comments on commit 7d60268

Please sign in to comment.