1<?php 2 /* libraries/graph.php 3 * 4 * Copyright (C) by Hugo Leisink <hugo@leisink.net> 5 * This file is part of the Banshee PHP framework 6 * http://www.banshee-php.org/ 7 */ 8 9 class graph { 10 private static $instances = 0; 11 private $graph_id = null; 12 private $output = null; 13 private $height = 150; 14 private $width = 500; 15 private $title = null; 16 private $bars = array(); 17 private $class = array(); 18 private $links = array(); 19 private $maxy_width = 50; 20 21 /* Constructor 22 * 23 * INPUT: - 24 * OUTPUT: - 25 * ERROR: - 26 */ 27 public function __construct($output) { 28 $this->output = $output; 29 $this->graph_id = ++self::$instances; 30 } 31 32 /* Magic method set 33 * 34 * INPUT: string key, mixed value 35 * OUTPUT: - 36 * ERROR: - 37 */ 38 public function __set($key, $value) { 39 switch ($key) { 40 case "height": $this->height = $value; break; 41 case "title": $this->title = $value; break; 42 case "width": $this->width = $value; break; 43 } 44 } 45 46 /* Add a bar to the graph 47 * 48 * INPUT: mixed x, integer y, string class[, string link] 49 * OUTPUT: - 50 * ERROR: - 51 */ 52 public function add_bar($x, $y, $class, $link = null) { 53 $this->bars[$x] = $y; 54 $this->class[$x] = $class; 55 if ($link != null) { 56 $this->links[$x] = $link; 57 } 58 } 59 60 /* Convert a big number to a more readable one 61 * 62 * INPUT: integer number 63 * OUTPUT: string number 64 * ERROR: - 65 */ 66 static public function readable_number($number) { 67 if ($number > 1000000000) { 68 return sprintf("%0.1f G", $number / 1000000000); 69 } else if ($number > 1000000) { 70 return sprintf("%0.1f M", $number / 1000000); 71 } else if ($number > 1000) { 72 return sprintf("%0.1f k", $number / 1000); 73 } 74 75 return $number; 76 } 77 78 /* Graph to output 79 * 80 * INPUT: - 81 * OUTPUT: - 82 * ERROR: - 83 */ 84 public function to_output() { 85 if (($bar_count = count($this->bars)) == 0) { 86 return; 87 } 88 89 $max_y = 100; 90 foreach ($this->bars as $y) { 91 if ($y > $max_y) { 92 $max_y = $y; 93 } 94 } 95 96 $this->output->add_css("banshee/graph.css"); 97 $this->output->add_javascript("banshee/graph.js"); 98 99 $params = array( 100 "id" => $this->graph_id, 101 "height" => $this->height, 102 "width" => $this->width, 103 "max_y" => $this->readable_number($max_y), 104 "bar_width" => sprintf("%0.2f", $this->width / $bar_count), 105 "maxy_width" => $this->maxy_width); 106 $this->output->open_tag("graph", $params); 107 if ($this->title !== NULL) { 108 $this->output->add_tag("title", $this->title); 109 } 110 foreach ($this->bars as $x => $y) { 111 $bar_y = ($max_y == 0) ? 0 : sprintf("%0.2f", $y * $this->height / $max_y); 112 $params = array( 113 "text" => $x, 114 "value" => $this->readable_number($y), 115 "class" => $this->class[$x]); 116 if ($this->links[$x] !== null) { 117 $params["link"] = $this->links[$x]; 118 } 119 $this->output->add_tag("bar", $bar_y, $params); 120 } 121 $this->output->close_tag(); 122 } 123 } 124?> 125