1: <?php
2:
3: namespace BN;
4:
5: class AggregateFunctions
6: {
7: private $zero;
8:
9: public function __construct()
10: {
11: $this->zero = new Number('0');
12: }
13:
14: public function sum(array $operands)
15: {
16: if (count($operands) == 0) {
17: return $this->zero;
18: }
19: $sum = array_shift($operands);
20: foreach ($operands as $o) {
21: $sum = $sum->add($o);
22: }
23: return $sum;
24: }
25:
26: public function count(array $operands)
27: {
28: $count = count($operands);
29: return new Number((string) $count);
30: }
31:
32: public function avg(array $operands)
33: {
34: $sum = $this->sum($operands);
35: $count = $this->count($operands);
36: return $count->isZero() ? $this->zero : $sum->divide($count);
37: }
38:
39: public function min(array $operands)
40: {
41: return $this->findExtreme($operands, 'isSmallerThan');
42: }
43:
44: public function max(array $operands)
45: {
46: return $this->findExtreme($operands, 'isBiggerThan');
47: }
48:
49: private function findExtreme(array $operands, $compareMethod)
50: {
51: $extreme = array_shift($operands);
52: foreach ($operands as $o) {
53: if ($o->$compareMethod($extreme)) {
54: $extreme = $o;
55: }
56: }
57: return $extreme;
58: }
59: }
60: