1: <?php
2: /**
3: * URL generation utility for controllers
4: *
5: * @category Horde
6: * @package Controller
7: * @author Mike Naberezny <mike@maintainable.com>
8: * @author Derek DeVries <derek@maintainable.com>
9: * @author Chuck Hagenbuch <chuck@horde.org>
10: * @license http://www.horde.org/licenses/bsd BSD
11: */
12: class Horde_Controller_UrlWriter
13: {
14: /**
15: * Defaults to merge into route parameters when not using named routes.
16: * @var array
17: */
18: protected $_defaults;
19:
20: /**
21: * @var Horde_Routes_Util
22: */
23: protected $_utils;
24:
25: /**
26: * Class constructor
27: *
28: * @param Horde_Routes_Utils $utils Route utilities
29: * @param array $defaults Defaults to merge for urlFor()
30: */
31: public function __construct(Horde_Routes_Utils $utils, $defaults = array())
32: {
33: $this->_utils = $utils;
34: $this->_defaults = $defaults;
35: }
36:
37: /**
38: * Generate a URL. Same signature as Horde_Routes_Utils->urlFor().
39: *
40: * @param $first mixed
41: * @param $second mixed
42: * @return string
43: */
44: public function urlFor($first, $second = array())
45: {
46: // anonymous route: serialize to params & merge defaults
47: // urlFor(array('controller' => 'books'))
48: if (is_array($first)) {
49: $first = array_merge($this->_defaults,
50: $this->_serializeToParams($first));
51: }
52:
53: // named route: serialize to params only (no merge)
54: // urlFor('notes', array('action' => 'show', 'id' => 1))
55: if (is_array($second)) {
56: $second = $this->_serializeToParams($second);
57: }
58:
59: // url generation "route memory" is not useful here
60: $this->_utils->mapperDict = array();
61:
62: // generate url
63: return $this->_utils->urlFor($first, $second);
64: }
65:
66: /**
67: * Serialize any objects in the collection supporting toParam() before
68: * passing the collection to Horde_Routes.
69: *
70: * @param array $collection
71: * @param array
72: */
73: protected function _serializeToParams($collection)
74: {
75: foreach ($collection as &$value) {
76: if (is_object($value) && method_exists($value, 'toParam')) {
77: $value = $value->toParam();
78: }
79: }
80: return $collection;
81: }
82: }
83: