Completed
Pull Request — master (#163)
by Corey
05:18
created

Graph::create()   B

Complexity

Conditions 8
Paths 48

Size

Total Lines 95
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 95
rs 7.9119
c 0
b 0
f 0
cc 8
nc 48
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace common\components;
3
4
use yii;
5
use Amenadiel\JpGraph\Graph as JpGraph;
6
use Amenadiel\JpGraph\Plot\Plot;
7
use Amenadiel\JpGraph\Plot\AccBarPlot;
8
use Amenadiel\JpGraph\Plot\GroupBarPlot;
9
use Amenadiel\JpGraph\Plot\BarPlot;
10
11
/**
12
 * Graph is a collection of functions related to the score chart that is used
13
 * in the email report and when a user makes their check-in scores public
14
 */
15
class Graph extends \yii\base\BaseObject {
16
  private $user;
17
18
  public function __construct(\common\interfaces\UserInterface $user, $config = []) {
19
    $this->user = $user;
20
    parent::__construct($config);
21
  }
22
23
  /**
24
   * Returns the filepath location of the generated graph image
25
   *
26
   * @return string the graph image filepath
27
   */
28
  public function getFilepath() {
29
    $path = Yii::getAlias('@graphImgPath');
30
    $filename = $this->user->getIdHash() . ".png";
0 ignored issues
show
Bug introduced by
The method getIdHash() does not exist on common\interfaces\UserInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to common\interfaces\UserInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

30
    $filename = $this->user->/** @scrutinizer ignore-call */ getIdHash() . ".png";
Loading history...
31
    return $path. '/' . $filename;
32
  }
33
34
  /**
35
   * Returns the URL of the generated graph image
36
   *
37
   * @return string the graph image URL
38
   */
39
  public function getUrl() {
40
    $filename = $this->user->getIdHash() . ".png";
41
    return \yii\helpers\Url::to("@graphImgUrl/$filename", true);
42
  }
43
44
  /**
45
   * Deletes the graph image
46
   */
47
  public function destroy() {
48
    $filepath = $this->getFilepath();
49
    @unlink($filepath);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

49
    /** @scrutinizer ignore-unhandled */ @unlink($filepath);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
50
  }
51
52
  /**
53
   * Creates the graph image
54
   *
55
   * Generates the graph image according to the values passed in by $values. It
56
   * always returns the in-memory image, saving the image to disk is optionally
57
   * specified with the $toDisk boolean.
58
   *
59
   * @param array $values an associative array of dates => scores
60
   * @param bool $toDisk used to specify whether or not to save the generated image to disk at the filepath returned by getFilepath(). Defaults to false.
61
   * @return string the encoded image
62
   */
63
  public function create(array $checkins, bool $toDisk = false) {
64
    if($toDisk) {
65
      // wipe out the current image, if it exists
66
      $this->destroy();
67
    }
68
69
    $accum = [];
70
    foreach($checkins as $checkin_sum) {
71
      for($i = 1; $i <= 7; $i ++) {
72
        $accum[$i][] = array_key_exists($i, $checkin_sum) ? $checkin_sum[$i]['count'] : 0;
73
      }
74
    }
75
76
    // Create the graph. These two calls are always required
77
    $graph = new JpGraph\Graph(800, 600, 'auto');
78
    $graph->SetImgFormat('png');
79
    $graph->img->SetImgFormat('png');
80
    $graph->SetScale("textlin");
81
    $graph->img->SetMargin(60, 60, 40, 140);
82
    $graph->img->SetAntiAliasing();
83
84
    //$graph->yaxis->SetTickPositions(array(0,50,100,150,200,250,300,350), array(25,75,125,175,275,325));
85
    $graph->SetShadow();
86
    $graph->ygrid->SetFill(false);
87
88
    // Setup dates as labels on the X-axis
89
    $graph->xaxis->SetTickLabels(array_keys($checkins));
90
    $graph->xaxis->HideTicks(false,false);
91
    $graph->yaxis->scale->SetAutoMin(0);
92
    $graph->yaxis->HideLine(false);
93
    $graph->yaxis->HideTicks(false,false);
94
    $graph->xaxis->SetLabelAngle(45);
95
    $graph->xaxis->SetFont(FF_ARIAL, FS_NORMAL, 10);
96
    $graph->yaxis->SetFont(FF_ARIAL, FS_NORMAL, 15);
97
98
    $category = Yii::$container->get(\common\interfaces\CategoryInterface::class);
99
100
    // Create the bar plots
101
    $plots = [];
102
    foreach($accum as $category_key => $category_data) {
103
      $bplot = new BarPlot($category_data);
104
      $color = $category::$colors[$category_key]['color'];
105
106
      $bplot->SetColor($color);
107
      $bplot->SetFillColor($color);
108
      $bplot->SetLegend(($category::getCategories())[$category_key]);
109
110
      $plots[] = $bplot;
111
    }
112
113
    $gbbplot = new AccBarPlot($plots);
114
    $graph->Add($gbbplot);
115
116
    // $graph->legend->SetFrameWeight(1);
117
    $graph->legend->SetColumns(3);
118
    $graph->legend->SetColor('#4E4E4E','#00A78A');
119
120
    $graph->title->SetFont(FF_ARIAL, FS_BOLD, 20);
121
    $graph->title->Set("Behaviors broken down by Category");
122
123
/*
124
125
    $graph = new JpGraph\Graph(800, 600);
126
    $graph->SetImgFormat('png');
127
    $graph->img->SetImgFormat('png');
128
    $graph->img->SetMargin(60, 60, 40, 140);
129
    $graph->img->SetAntiAliasing();
130
    $graph->SetScale("textlin");
131
    $graph->yaxis->scale->SetAutoMin(0);
132
    $graph->yaxis->SetLabelFormatCallback('floor');
133
    $graph->SetShadow();
134
    $graph->title->Set("Last month's scores");
135
    $graph->title->SetFont(FF_ARIAL, FS_BOLD, 20);
136
    $graph->xaxis->SetLabelAngle(45);
137
    $graph->xaxis->SetTickLabels($dates);
138
    $graph->xaxis->SetFont(FF_ARIAL, FS_NORMAL, 15);
139
    $graph->yaxis->SetFont(FF_ARIAL, FS_NORMAL, 15);
140
    $graph->Add($p1);
141
 */
142
    $img = $graph->Stroke(_IMG_HANDLER);
143
144
    ob_start();
145
    imagepng($img);
146
    $img_data = ob_get_clean();
147
148
    if($toDisk) {
149
      $filepath = $this->getFilepath(); 
150
      if(!is_dir(dirname($filepath))) {
151
        mkdir(dirname($filepath), 0766, true);
152
      }
153
154
      file_put_contents($filepath, $img_data, LOCK_EX);
155
    }
156
157
    return $img_data;
158
  }
159
}
160