Passed
Pull Request — master (#163)
by Corey
02:37
created

Graph::create()   B

Complexity

Conditions 8
Paths 48

Size

Total Lines 96
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 45
dl 0
loc 96
rs 7.9555
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
    // Create the graph. These two calls are always required
70
    $graph = new JpGraph\Graph(800, 600, 'auto');
71
    $graph->SetImgFormat('png');
72
    $graph->img->SetImgFormat('png');
73
    $graph->SetScale("textlin");
74
    $graph->img->SetMargin(60, 60, 40, 140);
75
    $graph->img->SetAntiAliasing();
76
77
    //$graph->yaxis->SetTickPositions(array(0,50,100,150,200,250,300,350), array(25,75,125,175,275,325));
78
    $graph->SetShadow();
79
    $graph->ygrid->SetFill(false);
80
81
    // Setup dates as labels on the X-axis
82
    $graph->xaxis->SetTickLabels(array_keys($checkins));
83
    $graph->xaxis->HideTicks(false,false);
84
    $graph->yaxis->scale->SetAutoMin(0);
85
    $graph->yaxis->HideLine(false);
86
    $graph->yaxis->HideTicks(false,false);
87
    $graph->xaxis->SetLabelAngle(45);
88
    $graph->xaxis->SetFont(FF_ARIAL, FS_NORMAL, 10);
89
    $graph->yaxis->SetFont(FF_ARIAL, FS_NORMAL, 15);
90
91
    $category = Yii::$container->get(\common\interfaces\CategoryInterface::class);
92
93
    // format the data into something nicer
94
    $accum = [];
95
    foreach($checkins as $checkin_sum) {
96
      for($i = 1; $i <= 7; $i ++) {
97
        $accum[$i][] = array_key_exists($i, $checkin_sum) ? $checkin_sum[$i]['count'] : 0;
98
      }
99
    }
100
101
    // Create the bar plots
102
    $plots = [];
103
    foreach($accum as $category_key => $category_data) {
104
      $bplot = new BarPlot($category_data);
105
      $color = $category::$colors[$category_key]['color'];
106
107
      $bplot->SetColor($color);
108
      $bplot->SetFillColor($color);
109
      $bplot->SetLegend(($category::getCategories())[$category_key]);
110
111
      $plots[] = $bplot;
112
    }
113
114
    $gbbplot = new AccBarPlot($plots);
115
    $graph->Add($gbbplot);
116
117
    // $graph->legend->SetFrameWeight(1);
118
    $graph->legend->SetColumns(3);
119
    $graph->legend->SetColor('#4E4E4E','#00A78A');
120
121
    //$graph->title->SetFont(FF_ARIAL, FS_BOLD, 20);
122
    //$graph->title->Set("Behaviors by category over time");
123
124
/*
125
126
    $graph = new JpGraph\Graph(800, 600);
127
    $graph->SetImgFormat('png');
128
    $graph->img->SetImgFormat('png');
129
    $graph->img->SetMargin(60, 60, 40, 140);
130
    $graph->img->SetAntiAliasing();
131
    $graph->SetScale("textlin");
132
    $graph->yaxis->scale->SetAutoMin(0);
133
    $graph->yaxis->SetLabelFormatCallback('floor');
134
    $graph->SetShadow();
135
    $graph->title->Set("Last month's scores");
136
    $graph->title->SetFont(FF_ARIAL, FS_BOLD, 20);
137
    $graph->xaxis->SetLabelAngle(45);
138
    $graph->xaxis->SetTickLabels($dates);
139
    $graph->xaxis->SetFont(FF_ARIAL, FS_NORMAL, 15);
140
    $graph->yaxis->SetFont(FF_ARIAL, FS_NORMAL, 15);
141
    $graph->Add($p1);
142
 */
143
    $img = $graph->Stroke(_IMG_HANDLER);
144
145
    ob_start();
146
    imagepng($img);
147
    $img_data = ob_get_clean();
148
149
    if($toDisk) {
150
      $filepath = $this->getFilepath(); 
151
      if(!is_dir(dirname($filepath))) {
152
        mkdir(dirname($filepath), 0766, true);
153
      }
154
155
      file_put_contents($filepath, $img_data, LOCK_EX);
156
    }
157
158
    return $img_data;
159
  }
160
}
161