Advertisement
TheFan1968

FusionCharts: PHP-Wrapper-Class

Jan 18th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.53 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Kvberlin\FusionCharts;
  4.  
  5. use Zend\Config\Factory;
  6. use Zend\Debug\Debug;
  7.  
  8.  
  9. /**
  10.  * ZendFramework3 Fusion
  11.  * Autor: Peter Wendel (ITA),- 897
  12.  * Datum: 01.12.2017
  13.  *
  14.  * Kurzbeschreibung:
  15.  * Neue Version der Klasse FusionCharts
  16.  *
  17.  * @license   http://framework.zend.com/license/new-bsd New BSD License
  18.  * Created by PhpStorm.
  19.  */
  20. class Fusion
  21. {
  22.     const FUSION_VERSION = 'v1.0.1 albernerAal';
  23.  
  24.     /**
  25.      * @var string
  26.      */
  27.     private $constructorTemplate = '
  28.        <script type="text/javascript">
  29.            FusionCharts.ready(function () {
  30.                new FusionCharts(__constructorOptions__);
  31.            });
  32.        </script>';
  33.  
  34.     /**
  35.      * @var string
  36.      */
  37.     private $renderTemplate = '
  38.        <script type="text/javascript">
  39.            FusionCharts.ready(function () {
  40.                FusionCharts("__chartId__").render();
  41.            });
  42.        </script>
  43.        ';
  44.  
  45.     /**
  46.      * Datenformat festlegen
  47.      * @var string
  48.      */
  49.     private $dataFormat = 'json';
  50.  
  51.     /**
  52.      * Gibt das fertige Html zurück.
  53.      * @var string
  54.      */
  55.     private $chartHtml;
  56.  
  57.     /**
  58.      * Typ des ausgewählten Charts
  59.      * @var string
  60.      */
  61.     private $chartType;
  62.  
  63.     /**
  64.      * Legt eine eineindeuitge Id des DIVs an, in dem gereandert werden soll.
  65.      * @var string
  66.      */
  67.     private $chartId;
  68.  
  69.     /**
  70.      * Canvas-Breite
  71.      * @var int
  72.      */
  73.     private $width= 400;
  74.  
  75.     /**
  76.      * Canvas Höhe
  77.      * @var int
  78.      */
  79.     private $height = 300;
  80.  
  81.     /**
  82.      *
  83.      * Eindeutige DIV-Id zur Erzeugung.
  84.      * @var string
  85.      */
  86.     private $divId;
  87.  
  88.     /**
  89.      * Eintrag der Datenquelle/Optionen
  90.      * @var string
  91.      */
  92.     private $dataSource = '';
  93.  
  94.     /**
  95.      * Enthält den gesamten Inhalt der Config-Datei
  96.      * @var array|\Zend\Config\Config
  97.      */
  98.     private $fusionChart=[];
  99.  
  100.     /**
  101.      * Globale Chart-Optionen
  102.      * @var array|mixed
  103.      */
  104.     private $globalOptions=[];
  105.  
  106.     /**
  107.      * Benutzerdefinierte Chart-Optionen
  108.      * @var array
  109.      */
  110.     private $customOptions=[];
  111.  
  112.     /**
  113.      * Besondere Optionen des speziellen ChartTyps
  114.      * @var array
  115.      */
  116.     private $chartOptions = [];
  117.  
  118.     /**
  119.      * Gesamt-Array-Options
  120.      * @var array
  121.      */
  122.     private $finalOptions=[];
  123.  
  124.     /**
  125.      * Die Daten, die angezeigt werden sollen
  126.      * @var array
  127.      */
  128.     private $chartData;
  129.  
  130.     /**
  131.      * Daten für die Kategorien, sofern für das Chart benötigt
  132.      * @var array
  133.      */
  134.     private $catData;
  135.  
  136.     /**
  137.      * @var array
  138.      */
  139.     private $trendlineData;
  140.  
  141.     /**
  142.      * @var array
  143.      */
  144.     private $customConfig;
  145.  
  146.     /**
  147.      * @var array
  148.      */
  149.     private $colors = ['#FF9900','#FFC500','#1B0FB5','#0857AA','#FFB545','#FFD445','#5C52DC','#468DD7','#FF9D0C','#FFC70C','#3326D5','#1972CF'];
  150.  
  151.     /*
  152.      * Chart-Typen
  153.      */
  154.     const FC_COLUMN_2D              = 'column2d';
  155.     const FC_PIE_2D                 = 'pie2d';
  156.     const FC_MULTISERIES_COLUMN_2D  = 'mscolumn2d';
  157.     const FC_STACKED_COLUMN_2D      = 'stackedcolumn2d';
  158.     const FC_DOUGHNUT_2D            = 'doughnut2d';
  159.     const FC_DOUGHNUT_3D            = 'doughnut3d';
  160.     const FC_MARIMEKKO              = 'marimekko';
  161.     const FC_BUBBLE_CHART_2D        = 'bubble';
  162.     const FC_BAR_2D                 = 'bar2d';
  163.  
  164.     /**
  165.      * Fusion constructor.
  166.      */
  167.     public function __construct(){
  168.         $this->setChartId();
  169.         $this->setDivId();
  170.         $this->setChartType(self::FC_COLUMN_2D);
  171.         $this->fusionChart = Factory::fromFile(__DIR__.'/fusion_charts_config.php');
  172.         $this->globalOptions = $this->fusionChart['global'];
  173.     }
  174.  
  175.     /**
  176.      * Benutzerdefinierte Chart-Options setzen
  177.      * @param string $option
  178.      * @param string $value
  179.      */
  180.     public function setChartOption(string $option, string $value){
  181.         @$this->customOptions[$option] = $value;
  182.     }
  183.  
  184.     /**
  185.      * Nach einer bestimmten Option fragen.
  186.      * @param string $option
  187.      * @return mixed|null
  188.      */
  189.     public function getChartOption(string $option){
  190.         $array = $this->getFinalOptions();
  191.         $ret = array_key_exists($option) ? $array[$option] : null;
  192.         return $ret;
  193.     }
  194.  
  195.     /**
  196.      * @param string|null $chartId
  197.      */
  198.     public function setChartId(string $chartId = null){
  199.         $this->chartId = is_null($chartId) ? 'fusion_chart_' . mt_rand(0, 100000) : $chartId;
  200.     }
  201.  
  202.     /**
  203.      * @return string
  204.      */
  205.     public function getChartId(){
  206.         return $this->chartId;
  207.     }
  208.  
  209.     /**
  210.      * @param string|null $divId
  211.      */
  212.     public function setDivId(string $divId=null){
  213.         $this->divId = is_null($divId) ? 'div_id_' . mt_rand(0, 100000) : $divId;
  214.     }
  215.  
  216.     /**
  217.      * @return string
  218.      */
  219.     public function getDivId(){
  220.         return $this->divId;
  221.     }
  222.  
  223.     /**
  224.      * @param int $width
  225.      * @param int $height
  226.      */
  227.     public function setCanvasSize(int $width = 400, int $height =300){
  228.         $this->width = $width;
  229.         $this->height = $height;
  230.     }
  231.  
  232.     /**
  233.      * @return int
  234.      */
  235.     public function getCanvasWidth(){
  236.         return $this->width;
  237.     }
  238.  
  239.     /**
  240.      * @return int
  241.      */
  242.     public function getCanvasHeight(){
  243.         return $this->height;
  244.     }
  245.  
  246.     /**
  247.      * @param $dataSource
  248.      */
  249.     public function setDataSource($dataSource){
  250.         $this->dataSource = $dataSource;
  251.     }
  252.  
  253.     /**
  254.      * @return string
  255.      */
  256.     public function getDataSource(){
  257.         return $this->dataSource;
  258.     }
  259.  
  260.     /**
  261.      * @param string $format
  262.      */
  263.     public function setDataFormat($format = 'json'){
  264.         $this->dataFormat = $format;
  265.     }
  266.  
  267.     /**
  268.      * @return string
  269.      */
  270.     public function getDataFormat(){
  271.         return $this->dataFormat;
  272.     }
  273.  
  274.     /**
  275.      * @param string $chartType
  276.      */
  277.     public function setChartType(string $chartType){
  278.         $this->chartType = $chartType;
  279.     }
  280.  
  281.     /**
  282.      * @return string
  283.      */
  284.     public function getChartType(){
  285.         return $this->chartType;
  286.     }
  287.  
  288.     /**
  289.      * Schreibt die Werte der Constructor-Options in den Quelltext:
  290.      * type,id,width,height,divId,dataFormat, dataSource
  291.      */
  292.     private function writeHtmlText(){
  293.         $tempArray = [
  294.             'type'      => $this->getChartType(),
  295.             'id'        => $this->getChartId(),
  296.             'width'     => $this->getCanvasWidth(),
  297.             'height'    => $this->getCanvasHeight(),
  298.             'renderAt'  => $this->getDivId(),
  299.             'dataFormat'=> $this->getDataFormat(),
  300.             'dataSource'=> '__dataSource__'
  301.         ];
  302.  
  303.         $jsonEncodedOptions = json_encode($tempArray);
  304.  
  305.         $this->dataSource= $this->getFinalOptions();
  306.  
  307.         if ($this->dataFormat === 'json') {
  308.             $jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', json_encode($this->dataSource), $jsonEncodedOptions);
  309.         } elseif ($this->dataFormat === 'xml') {
  310.             $jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', '\'__dataSource__\'', $jsonEncodedOptions);
  311.             $jsonEncodedOptions = preg_replace('/__dataSource__/', json_encode($this->dataSource), $jsonEncodedOptions);
  312.         } elseif ($this->dataFormat === 'xmlurl') {
  313.             $jsonEncodedOptions = preg_replace('/__dataSource__/', json_encode($this->dataSource), $jsonEncodedOptions);
  314.         } elseif ($this->dataFormat === 'jsonurl') {
  315.             $jsonEncodedOptions = preg_replace('/__dataSource__/', json_encode($this->dataSource), $jsonEncodedOptions);
  316.         }
  317.         $this->chartHtml = preg_replace('/__constructorOptions__/', $jsonEncodedOptions, $this->constructorTemplate);
  318.     }
  319.  
  320.  
  321.     /**
  322.      * render the chart created
  323.      * It prints a script and calls the FusionCharts javascript render method of created chart
  324.      *
  325.      * @return string
  326.      */
  327.     function render() {
  328.         $this->writeHtmlText();
  329.         $renderHTML = preg_replace('/__chartId__/', $this->getChartId(), $this->renderTemplate);
  330.         return $this->chartHtml."\n".$renderHTML;
  331.     }
  332.  
  333.     /**
  334.      * Generiert die finalOptions, die zum Rendern benutzt werden.
  335.      * Setzt diese aus allen konfigurierten Daten zusammen:
  336.      * - Options
  337.      * - Kategorien
  338.      * - Trendlines
  339.      */
  340.     private function setFinalOptions(){
  341.         // Optionen aus dem Bereich "Chart"
  342.         $this->finalOptions['chart'] = array_merge(
  343.             $this->globalOptions,
  344.             $this->chartOptions,
  345.             $this->customOptions
  346.         );
  347.         // Angabe von Kategorien, sofern benötigt
  348.         if (isset($this->catData)) {
  349.             $this->finalOptions['categories'] = $this->getCategories();
  350.         }
  351.         if (isset($this->trendlineData)){
  352.             $this->finalOptions['trendlines'] = $this->getTrendlines();
  353.         }
  354.         if (array_key_exists('data',$this->getChartData())):
  355.             $this->finalOptions['dataset']= $this->getChartData();
  356.             //Debug::dump($this->getChartData(),'<h4>ChartData - Fusion</h4>');
  357.         else:
  358.             $this->finalOptions['data']=$this->getChartData();
  359.         endif;
  360.     }
  361.  
  362.     /**
  363.      * Gesamt-Array aller Optionen des Charts
  364.      * @return array
  365.      */
  366.     public function getFinalOptions(){
  367.         $this->setFinalOptions();
  368.         return $this->finalOptions;
  369.     }
  370.  
  371.     /**
  372.      * Spezielle Chart-Typ-Options (von der Chart-Klasse abgelegt)
  373.      * @param array $options
  374.      */
  375.     public function setChartTypeOptions(array $options){
  376.         $this->chartOptions = $options;
  377.     }
  378.  
  379.     /**
  380.      * Spezielle Chart-Typ-Options
  381.      * @return array
  382.      */
  383.     public function getChartTypeOptions(){
  384.         return $this->chartOptions;
  385.     }
  386.  
  387.     public function setCategories(array $cats){
  388.         /**
  389.          * Ausgangsarray
  390.          * [ Cat1, Cat2, Cat3, Cat4....]
  391.          * oder
  392.          * [ Cat1 => [x-value, showverticalline],Cat2 => [..,..],...  ]
  393.          */
  394.         foreach($cats as $key => $value):
  395.  
  396.             $array = is_array($value) ? [
  397.                 'label' => $key,
  398.                 'x' => $value[0],
  399.                 'showverticalline' => $value[1]
  400.             ] : ['label' => $value];
  401.             @$catArray['category'][]=$array;
  402.         endforeach;
  403.         $this->catData = $catArray;
  404.     }
  405.  
  406.     public function getCategories(){
  407.         return $this->catData;
  408.     }
  409.  
  410.     /**
  411.      * Hier eingeworfene Arrays werden passend zum Chart-Typ
  412.      * in Data-Sets für die Anzeige umgewandelt.
  413.      * @param string $chartType
  414.      * @param array $data
  415.      */
  416.     public function setChartData(string $chartType, array $data){
  417.  
  418.         switch ($chartType):
  419.             case self::FC_STACKED_COLUMN_2D:
  420.                 $this->setSeriesDataArray($data);
  421.                 break;
  422.             case self::FC_MARIMEKKO:
  423.                 $this->setSeriesDataArray($data);
  424.                 break;
  425.             case self::FC_BUBBLE_CHART_2D:
  426.                 $this->setBubbleDataArray($data);
  427.                 break;
  428.             case self::FC_MULTISERIES_COLUMN_2D:
  429.                 $this->setSeriesDataArray($data);
  430.                 break;
  431.             default:
  432.                 $this->setDefaultDataArray($data);
  433.                 break;
  434.         endswitch;
  435.     }
  436.  
  437.     /**
  438.      * Umwandlung in das Default-Data-Set für einfache Charts
  439.      * @param array $dataArray
  440.      */
  441.     private function setDefaultDataArray(array $dataArray){
  442.         /**
  443.          * Ausgangsarray:
  444.          * [ Labeltext => Wert ]
  445.          */
  446.         $data = [];
  447.         foreach($dataArray as $label => $value):
  448.             $array = [
  449.                 'label'     => $label,
  450.                 'value'     => $value
  451.             ];
  452.             @$data[]=$array;
  453.         endforeach;
  454.         $this->setDataArray($data);
  455.     }
  456.  
  457.     private function setSeriesDataArray(array $dataArray){
  458.         /**
  459.          * Ausgangsarray:
  460.          * [ Seriesname => array (wert1,wert2,wert3,wert4...) ]
  461.          */
  462.         $dataSet=[];
  463.         foreach ($dataArray as $series => $valueArray):
  464.             $array = [
  465.                 'seriesname'    => $series,
  466.                 'data'          => $valueArray
  467.             ];
  468.             @$dataSet[]=$array;
  469.         endforeach;
  470.         $this->setDataArray($dataSet);
  471.     }
  472.  
  473.     private function setBubbleDataArray(array $dataArray){
  474.         /**
  475.          * Ausgangsarray
  476.          * [ Name => [x, y, z] ]
  477.          */
  478.         @$BubbleSet['color'] = '#00aee4';
  479.         $z = 0;
  480.         foreach($dataArray as $key => $valueArray):
  481.             if ($z > 9) $z=0;
  482.             $array = [
  483.                 'x'     => $valueArray[0],
  484.                 'y'     => $valueArray[1],
  485.                 'z'     => $valueArray[2],
  486.                 'name'  => $key,
  487.                 'color' => $this->colors[$z]
  488.             ];
  489.         @$BubbleSet['data'][]=$array;
  490.         $z +=1;
  491.         endforeach;
  492.         $this->setDataArray($BubbleSet);
  493.     }
  494.  
  495.     /**
  496.      * Array für Data-Set setzen
  497.      * @param array $data
  498.      */
  499.     private function setDataArray(Array $data){
  500.         $this->chartData = $data;
  501.     }
  502.  
  503.     /**
  504.      * Array für das Data-Set holen
  505.      * @return mixed
  506.      */
  507.     public function getChartData(){
  508.         return $this->chartData;
  509.     }
  510.  
  511.     public function setTrendlines(array $data,bool $vTrendline=false){
  512.         /**
  513.          * Ausgangsarray:
  514.          * [ 'startvalue => 12205,'color' => '#0075c2',... ]
  515.          */
  516.         if($vTrendline):
  517.             if (!isset($this->trendlineData['vTrendlines'])) @$this->trendlineData['vTrendlines']['line'];
  518.             $this->trendlineData['vTrendlines']['line'][]=$data;
  519.         else:
  520.             if (!isset($this->trendlineData['trendlines'])) @$this->trendlineData['trendlines']['line'];
  521.             $this->trendlineData['trendlines']['line'][]=$data;
  522.         endif;
  523.     }
  524.  
  525.     public function getTrendlines(){
  526.         return $this->trendlineData;
  527.     }
  528.  
  529.     public function getConfig(string $abschnitt){
  530.         return array_key_exists($abschnitt, $this->fusionChart) ? $this->fusionChart[$abschnitt] : null;
  531.     }
  532.  
  533.     public function setCustomOption(array $options){
  534.         $this->customOptions = array_merge($this->customOptions,$options);
  535.     }
  536.  
  537.     public function setCustomConfigFile(string $path){
  538.         $this->customConfig = Factory::fromFile($path);
  539.     }
  540.  
  541.     public function getFromCustomConfigFile(string $abschnitt){
  542.         return array_key_exists($abschnitt, $this->customConfig) ? $this->customConfig[$abschnitt] : null;
  543.     }
  544. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement