9 * This source file is subject to the new BSD license that is bundled
10 * with this package in the file LICENSE.
11 * It is also available through the world-wide-web at this URL:
12 * http://phergie.org/license
15 * @package Phergie_Plugin_Php
16 * @author Phergie Development Team <team@phergie.org>
17 * @copyright 2008-2010 Phergie Development Team (http://phergie.org)
18 * @license http://phergie.org/license New BSD License
19 * @link http://pear.phergie.org/package/Phergie_Plugin_Php
23 * URL shortener abstract class
26 * @package Phergie_Plugin_Url
27 * @author Phergie Development Team <team@phergie.org>
28 * @license http://phergie.org/license New BSD License
29 * @link http://pear.phergie.org/package/Phergie_Plugin_Url
30 * @uses Phergie_Plugin_Http pear.phergie.org
32 abstract class Phergie_Plugin_Url_Shorten_Abstract
39 * @param Phergie_Plugin_Http $http instance of the http plugin
41 public function __construct(Phergie_Plugin_Http $http)
47 * Returns an array of request parameters given a url to shorten. The
48 * following keys are valid request parameters:
50 * * 'uri': the URI for the request (required)
51 * * 'query': an array of key-value pairs sent in a GET request
52 * * 'post': an array of key-value pairs sent in a POST request
53 * * 'callback': to be called after the request is finished. Should accept
54 * a Phergie_Plugin_Http_Response object and return either the shortened
55 * url or false if an error has occured.
57 * If the 'post' key is present a POST request shall be made; otherwise
58 * a GET request will be made. The 'post' key can be an empty array and
59 * a post request will still be made.
61 * If no callback is provided the contents of the response will be returned.
63 * @param string $url the url to shorten
65 * @return array the request parameters
67 protected abstract function getRequestParams($url);
70 * Shortens a given url.
72 * @param string $url the url to shorten
74 * @return string the shortened url or false on a failure
76 public function shorten($url)
78 $defaults = array('get' => array(), 'post' => array(), 'callback' => null);
79 $options = array('timeout' => 2);
80 $params = $this->getRequestParams($url) + $defaults;
82 // Should some kind of notice be thrown? Maybe just if getRequestParams does not return an array?
83 if (!is_array($params) || empty($params['uri'])) {
87 if (!empty($params['post'])) {
88 $response = $this->http->post($params['uri'], $params['get'], $params['post'], $options);
90 $response = $this->http->get($params['uri'], $params['get'], $options);
93 if (is_callable($params['callback'])) {
94 return call_user_func($params['callback'], $response);
97 $code = $response->getCode();
98 $content = trim($response->getContent);
99 if ($code < 200 || $code >= 300 || empty($content)) {
103 return $response->getContent();