* @license PHP License * @package WB * @subpackage db */ WBClass::load('WBDatasource_Decorator'); /** * Simple datasource decorator: Median * * @version 0.1.0 * @package WB * @subpackage db */ class WBDatasource_Decorator_Median extends WBDatasource_Decorator { /** * decorator's parameter list * * Parameters: * - columns: list of columns to decorate * - span: number of items to calculate average of * - format: number format as in sprintf() * * @var array */ protected $parameter = array( 'span' => 7, 'column' => array(), 'format' => '%d' ); /** * store values for each column to calculate average * @var array */ private $buffer = array(); /** * location of median values * @var array */ private $idx = array(); /** * setup column buffers */ public function onStart(&$item) { $this->parameter['span'] = intval($this->parameter['span']); foreach ($this->parameter['column'] as $c) {# $this->buffer[$c] = array(); $item[$c . '_med'] = null; } $this->pos[] = ceil($this->parameter['span'] / 2); if ($this->parameter['span'] % 2 == 0) { $this->pos[] = floor($this->parameter['span'] / 2); } } /** * actually decorate list item * * @param array $item * @return void */ public function decorate(&$item) { foreach ($this->buffer as $c => &$b) { if (count($b) >= $this->parameter['span']) { array_shift($b); } $b[] = $item[$c]; if (count($b) != $this->parameter['span']) { $item[$c . '_med'] = null; continue; } $x = $b[$this->pos[0]]; if (isset($this->pos[1])) { $x += $this->pos[1]; $x /= 2; } $item[$c . '_med'] = sprintf($this->parameter['format'], $x); } } } ?>