HtmlChart::run()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
namespace dynamikaweb\googlechart;
4
5
use yii\helpers\ArrayHelper;
6
use yii\helpers\Html;
7
use yii\helpers\Json;
8
use yii\web\View;
9
10
11
class HtmlChart extends \yii\base\Widget
12
{
13
    public $containerId;
14
15
    public $visualization;
16
17
    public $packages = 'corechart'; 
18
19
    public $loadVersion = "1.1";
20
21
    public $data = [];
22
23
    public $options = [];
24
    
25
    public $scriptAfterArrayToDataTable = '';
26
27
    public $htmlOptions = [];
28
29
    public $tag = "div";
30
31
    public function run()
32
    {
33
        $id = ArrayHelper::getValue($this->options, 'id', $this->getId());
34
        // if no container is set, it will create one
35
        if ($this->containerId == null) {
36
            $this->htmlOptions['id'] = 'div-chart' . $id;
37
            $this->containerId = $this->htmlOptions['id'];
38
            echo Html::tag($this->tag, null, $this->htmlOptions);
39
        }
40
        $this->registerClientScript($id);
41
    }
42
43
    /**
44
     * Registers required scripts
45
     */
46
    public function registerClientScript($id)
47
    {
48
        $jsData = Json::encode($this->data);
49
        $jsOptions = Json::encode($this->options);
50
        
51
        $script = '
52
			google.setOnLoadCallback(drawChart' . $id . ');
53
			function drawChart' . $id . '() {
54
				var data = google.visualization.arrayToDataTable(' . $jsData . ');
55
				' . $this->scriptAfterArrayToDataTable . '
56
				var options = ' . $jsOptions . ';
57
				' . $id . ' = new google.visualization.' . $this->visualization . '(document.getElementById("' . $this->containerId . '"));
58
				' . $id . '.draw(data, options);
59
			}';
60
61
        $view = $this->getView();
62
        $view->registerJsFile('https://www.google.com/jsapi',['position' => View::POS_HEAD]);
63
        $view->registerJs('google.load("visualization", "' . $this->loadVersion . '", {packages:["' . $this->packages . '"]});', View::POS_HEAD, __CLASS__ . '#' . $id);
64
        $view->registerJs($script, View::POS_HEAD, $id);
65
    }
66
}
67