Completed
Push — master ( ca3a89...f348a3 )
by Pavel
07:11 queued 04:12
created

ColumnsSummary::render()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 13
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
/**
4
 * @copyright   Copyright (c) 2015 ublaboo <[email protected]>
5
 * @author      Pavel Janda <[email protected]>
6
 * @package     Ublaboo
7
 */
8
9
namespace Ublaboo\DataGrid;
10
11
use Ublaboo\DataGrid\Column\ColumnNumber;
12
13
class ColumnsSummary
14
{
15
16
	/**
17
	 * @var DataGrid
18
	 */
19
	protected $datagrid;
20
21
	/**
22
	 * @var array
23
	 */
24
	protected $summary;
25
26
	/**
27
	 * @var array
28
	 */
29
	protected $format = [];
30
31
32
	/**
33
	 * @param DataGrid $datagrid
34
	 * @param array    $columns
35
	 */
36
	public function __construct(DataGrid $datagrid, array $columns)
37
	{
38
		$this->summary = array_fill_keys(array_values($columns), 0);
39
		$this->datagrid = $datagrid;
40
41
		foreach ($this->summary as $key => $sum) {
42
			$column = $this->datagrid->getColumn($key);
43
44
			if ($column instanceof ColumnNumber) {
45
				$arg = $column->getFormat();
46
				array_unshift($arg, $key);
47
48
				call_user_func_array([$this, 'setFormat'], $arg);
49
			}
50
		}
51
	}
52
53
54
	/**
55
	 * @param Row $row
56
	 */
57
	public function add(Row $row)
58
	{
59
		foreach ($this->summary as $key => $sum) {
60
			$column = $this->datagrid->getColumn($key);
61
			$value = $row->getValue($column->getColumn());
62
63
			$this->summary[$key] += $value;
64
		}
65
	}
66
67
68
	/**
69
	 * @param  string $key
70
	 * @return mixed
71
	 */
72
	public function render($key)
73
	{
74
		if (!isset($this->summary[$key])) {
75
			return NULL;
76
		}
77
78
		return number_format(
79
			$this->summary[$key],
80
			$this->format[$key][0],
81
			$this->format[$key][1],
82
			$this->format[$key][2]
83
		);
84
	}
85
86
87
	/**
88
	 * Set number format
89
	 * @param string $key
90
	 * @param int    $decimals
91
	 * @param string $dec_point
92
	 * @param string $thousands_sep
93
	 */
94
	public function setFormat($key, $decimals = 0, $dec_point = '.', $thousands_sep = ' ')
95
	{
96
		$this->format[$key] = [$decimals, $dec_point, $thousands_sep];
97
98
		return $this;
99
	}
100
101
102
	/**
103
	 * @param  array  $columns
104
	 * @return bool
105
	 */
106
	public function someColumnsExist(array $columns)
107
	{
108
		foreach ($columns as $key => $column) {
109
			if (isset($this->summary[$key])) {
110
				return TRUE;
111
			}
112
		}
113
114
		return FALSE;
115
	}
116
117
}
118