1 <?php
defined('SYSPATH') OR die('No direct access allowed.');
3 * [Tag cloud][ref-tcl] creation library.
5 * [ref-tcl]: http://en.wikipedia.org/wiki/Tag_cloud
7 * $Id: Tagcloud.php 3917 2009-01-21 03:06:22Z zombor $
11 * @copyright (c) 2008 Kohana Team
12 * @license http://kohanaphp.com/license.html
17 * Creates a new Tagcloud instance and returns it.
20 * @param array elements of the tagcloud
21 * @param integer minimum font size
22 * @param integer maximum font size
25 public static function factory(array $elements, $min_size = NULL, $max_size = NULL, $shuffle = FALSE)
27 return new Tagcloud($elements, $min_size, $max_size, $shuffle);
30 public $min_size = 80;
31 public $max_size = 140;
32 public $attributes = array('class' => 'tag');
33 public $shuffle = FALSE;
35 // Tag elements, biggest and smallest values
41 * Construct a new tagcloud. The elements must be passed in as an array,
42 * with each entry in the array having a "title" ,"link", and "count" key.
43 * Font sizes will be applied via the "style" attribute as a percentage.
45 * @param array elements of the tagcloud
46 * @param integer minimum font size
47 * @param integer maximum font size
50 public function __construct(array $elements, $min_size = NULL, $max_size = NULL, $shuffle = FALSE)
52 $this->elements
= $elements;
54 if($shuffle !== FALSE)
56 $this->shuffle
= TRUE;
60 foreach ($elements as $data)
62 $counts[] = $data['count'];
65 // Find the biggest and smallest values of the elements
66 $this->biggest
= max($counts);
67 $this->smallest
= min($counts);
69 if ($min_size !== NULL)
71 $this->min_size
= $min_size;
74 if ($max_size !== NULL)
76 $this->max_size
= $max_size;
81 * Magic __toString method. Returns all of the links as a single string.
85 public function __toString()
87 return implode("\n", $this->render());
91 * Renders the elements of the tagcloud into an array of links.
95 public function render()
97 if ($this->shuffle
=== TRUE)
99 shuffle($this->elements
);
102 // Minimum values must be 1 to prevent divide by zero errors
103 $range = max($this->biggest
- $this->smallest
, 1);
104 $scale = max($this->max_size
- $this->min_size
, 1);
106 // Import the attributes locally to prevent overwrites
107 $attr = $this->attributes
;
110 foreach ($this->elements
as $data)
112 if (strpos($data['title'], ' ') !== FALSE)
114 // Replace spaces with non-breaking spaces to prevent line wrapping
115 // in the middle of a link
116 $data['title'] = str_replace(' ', ' ', $data['title']);
119 // Determine the size based on the min/max scale and the smallest/biggest range
120 $size = ((($data['count'] - $this->smallest
) * $scale) / $range) +
$this->min_size
;
122 $attr['style'] = 'font-size: '.round($size, 0).'%';
124 $output[] = html
::anchor($data['link'], $data['title'], $attr)."\n";