1 <?php
2 /**
3 *
4 * WhSumOperation class
5 *
6 * Displays a total of specified column name
7 *
8 * @author Antonio Ramirez <amigo.cobos@gmail.com>
9 * @copyright Copyright © 2amigos.us 2013-
10 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
11 * @package YiiWheels.widgets.grid.operations
12 * @uses YiiWheels.widgets.grid.operations.WhOperation
13 */
14 Yii::import('yiiwheels.widgets.grid.operations.WhOperation');
15
16 class WhSumOperation extends WhOperation
17 {
18 /**
19 * @var float $total the total sum
20 */
21 protected $total;
22
23 /**
24 * @var array $supportedTypes the supported type of values
25 */
26 protected $supportedTypes = array('raw', 'text', 'ntext', 'number');
27
28
29 /**
30 * Widget's initialization method
31 * @throws CException
32 */
33 public function init()
34 {
35 parent::init();
36
37 if (!in_array($this->column->type, $this->supportedTypes)) {
38 throw new CException(Yii::t(
39 'zii',
40 'Unsupported column type. Supported column types are: "{types}"',
41 array(
42 '{types}' => implode(', ', $this->supportedTypes)
43 )
44 ));
45 }
46 }
47
48 /**
49 * Displays the summary
50 * @return mixed|void
51 */
52 public function displaySummary()
53 {
54 echo strtr(
55 $this->template,
56 array(
57 '{label}' => $this->label,
58 '{value}' => $this->total === null ? '' : Yii::app()->format->format($this->total, $this->column->type)
59 )
60 );
61 }
62
63 /**
64 * Process the value to calculate
65 * @param $value
66 * @return mixed|void
67 */
68 public function processValue($value)
69 {
70 // remove html tags as we cannot access renderDataCellContent from the column
71 $clean = strip_tags($value);
72 $this->total += ((float)$this->extractNumber($clean));
73 }
74
75 /**
76 * Extracts the digital part of the calculated value.
77 * @param int $value
78 * @return bool
79 */
80 protected function extractNumber($value)
81 {
82 preg_match_all('/([+-]?[0-9]+[,\.]?)+/', $value, $matches);
83 return !empty($matches[0]) && @$matches[0][0] ? $matches[0][0] : 0;
84 }
85 }