/mvc/components/shorturl
[return to app]1
<?php
2 class shorturlComponent {
3 /**
4 * Short URL logic to either display new URL form, forward to the URL associated with a Short URL or throw 404
error
5 */
6 public function __construct() {
7 if (isset(mvc::$params[0])) {
8 $model = get::model('shorturl');
9 $shortUrl = $model->getShortUrl(mvc::$params[0]);
10 if ($shortUrl) {
11 $model->logForward(mvc::$params[0]);
12 load::redirect($shortUrl);
13 } else {
14 mvc::$controller = get::$config->errorHandler; //404
15 mvc::$action = 'notFound';
16 return;
17 }
18 }
19 $this->_createShortUrl();
20 }
21
22 /**
23 * Create a new short URL
24 */
25 protected function _createShortUrl() {
26 if (isset($_POST['url'])) {
27 $_POST['url'] = trim($_POST['url']);
28 if (strpos($_POST['url'], 'http') !== 0) {
29 $_POST['url'] = 'http://' . $_POST['url'];
30 }
31 require_once get::$config->packagesPath() . 'validator';
32 $Validator = new Validator;
33 if (!filter_var($_POST['url'], FILTER_VALIDATE_URL) || !$Validator->isValidUrl($_POST['url'])) {
34 $_POST['errors']['url'] = 'URL does not appear to be valid';
35 } else {
36 $_POST['shortUrl'] = get::model('shorturl')->addShortUrl($_POST['url']);
37 }
38 }
39 }
40 }