From afc9d5a3ce941a067a66211eb4aecdc10fcf8be8 Mon Sep 17 00:00:00 2001 From: voltan Date: Sat, 31 Mar 2018 17:20:07 +0430 Subject: [PATCH] Add chart helper --- lib/Pi/View/Helper/Chart.php | 87 ++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 lib/Pi/View/Helper/Chart.php diff --git a/lib/Pi/View/Helper/Chart.php b/lib/Pi/View/Helper/Chart.php new file mode 100644 index 0000000000..bec0c6ff3a --- /dev/null +++ b/lib/Pi/View/Helper/Chart.php @@ -0,0 +1,87 @@ +chart($type, $data, $options, $htmlClass); + * + * @see http://www.chartjs.org + * @author Hossein Azizabadi + */ +class Chart extends AbstractHelper +{ + /** + * Load chart script + * + * @param string $type + * @param array $data + * @param array $options + * @param string $htmlClass + * + * @return $this + */ + public function __invoke($type, $data, $options = [], $htmlClass = 'pi-chart') + { + // Set uniqid + $id = uniqid('piChart'); + + // Sat data and option + $pattern = '/"([a-zA-Z]+[a-zA-Z0-9_]*)":/'; + $replacement = '$1:'; + $data = preg_replace($pattern, $replacement, json_encode($data)); + $options = empty($options) ? '{}' : preg_replace($pattern, $replacement, json_encode($options)); + + // Set script + $script + = <<<'EOT' +(function ($) { + $(document).ready(function () { + var ctx = document.getElementById('%s').getContext('2d'); + var %s = new Chart(ctx, { + type: '%s', + data: %s, + options: %s + }); + }); +})(jQuery) +EOT; + $script = sprintf( + $script, + $id, + $id, + $type, + $data, + $options + ); + + // Load chart + $this->view->jQuery(); + $this->view->js(pi::url('static/vendor/chart/Chart.min.js')); + $this->view->footScript()->appendScript($script); + + // render html + $htmlTemplate + = <<<'EOT' +
+ +
+EOT; + + $content = sprintf($htmlTemplate, $id, $htmlClass); + + return $content; + } +} \ No newline at end of file