1 <?php
2 /**
3 *
4 * WhCountOfTypeOperation class
5 *
6 * Renders a summary based on the count of specified types. For example, if a value has a type 'blue', this class will
7 * count the 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.WhOperation
14 */
15 Yii::import('yiiwheels.widgets.grid.operations.WhOperation');
16
17 class WhCountOfTypeOperation extends WhOperation
18 {
19 /**
20 * @var string $template
21 * @see parent class
22 */
23 public $template = '{label}: {types}';
24
25 /**
26 * @var string $typeTemplate holds the template of each calculated type
27 */
28 public $typeTemplate = '{label}({value})';
29
30 /**
31 * @var array $types hold the configuration of types to calculate. The configuration is set by an array which keys
32 * are the value types to count. You can set their 'label' independently.
33 *
34 * <pre>
35 * 'types' => array(
36 * '0' => array('label' => 'zeros'),
37 * '1' => array('label' => 'ones'),
38 * '2' => array('label' => 'twos')
39 * </pre>
40 */
41 public $types = array();
42
43
44 /**
45 * Widget's initialization
46 * @throws CException
47 */
48 public function init()
49 {
50 if (empty($this->types)) {
51 throw new CException(Yii::t(
52 'zii',
53 '"{attribute}" attribute must be defined',
54 array('{attribute}' => 'types')
55 ));
56 }
57 foreach ($this->types as $type) {
58 if (!isset($type['label'])) {
59 throw new CException(Yii::t('zii', 'The "label" of a type must be defined.'));
60 }
61 }
62 parent::init();
63 }
64
65 /**
66 * (no phpDoc)
67 * @see TbOperation
68 *
69 * @param $value
70 *
71 * @return mixed|void
72 */
73 public function processValue($value)
74 {
75 $clean = strip_tags($value);
76
77 if (array_key_exists($clean, $this->types)) {
78 if (!isset($this->types[$clean]['value'])) {
79 $this->types[$clean]['value'] = 0;
80 }
81 $this->types[$clean]['value'] += 1;
82 }
83 }
84
85 /**
86 * (no phpDoc)
87 * @see TbOperation
88 * @return mixed|void
89 */
90 public function displaySummary()
91 {
92 $typesResults = array();
93 foreach ($this->types as $type) {
94 if (!isset($type['value'])) {
95 $type['value'] = 0;
96 }
97
98 $typesResults[] = strtr(
99 $this->typeTemplate,
100 array('{label}' => $type['label'], '{value}' => $type['value'])
101 );
102 }
103 echo strtr($this->template, array('{label}' => $this->label, '{types}' => implode(' ', $typesResults)));
104 }
105 }
106