1 <?php
2 /**
3 *
4 * WhPercentOfTypeOperation class
5 *
6 * Renders a summary based on the percent count of specified types. For example, if a value has a type 'blue', this class will
7 * count the percentage number of times the value 'blue' has on that column.
8 *
9 * @author Antonio Ramirez <amigo.cobos@gmail.com>
10 * @copyright Copyright © 2amigos.us 2013-
11 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
12 * @package YiiWheels.widgets.grid.operations
13 * @uses YiiWheels.widgets.grid.operations.WhCountOfTypeOperation
14 */
15 Yii::import('yiiwheels.widgets.grid.operations.WhCountOfTypeOperation');
16
17 class WhPercentOfTypeOperation extends WhCountOfTypeOperation
18 {
19 /**
20 * @var string $typeTemplate
21 * @see TbCountOfTypeOperation
22 */
23 public $typeTemplate = '{label}({value}%)';
24
25 /**
26 * @var integer $_total holds the total sum of the values. Required to get the percentage.
27 */
28 protected $_total;
29
30
31 /**
32 * @return mixed|void
33 * @see TbOperation
34 */
35 public function displaySummary()
36 {
37 $typesResults = array();
38
39 foreach ($this->types as $type) {
40 if (!isset($type['value'])) {
41 $type['value'] = 0;
42 }
43
44 $type['value'] = $this->getTotal() ? number_format((float)($type['value'] / $this->getTotal()) * 100, 1)
45 : 0;
46 $typesResults[] = strtr(
47 $this->typeTemplate,
48 array('{label}' => $type['label'], '{value}' => $type['value'])
49 );
50 }
51
52 echo strtr($this->template, array('{label}' => $this->label, '{types}' => implode(' ', $typesResults)));
53 }
54
55 /**
56 * Returns the total of types
57 * @return int holds
58 */
59 protected function getTotal()
60 {
61 if (null == $this->_total) {
62 $this->_total = 0;
63 foreach ($this->types as $type) {
64 if (isset($type['value'])) {
65 $this->_total += $type['value'];
66 }
67 }
68 }
69 return $this->_total;
70 }
71 }
72