Graph::destroy()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
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 behaviors chart that is used
13
 * in the email report and when a user makes their check-in behaviors 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 => check-in summary
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
70
    $graph = new JpGraph\Graph(800, 600, 'auto');
71
    $graph->title->Set("Last 30 Days of Selected Behaviors");
72
    $graph->title->SetFont(FF_ARIAL, FS_BOLD, 20);
73
    $graph->SetImgFormat('png');
74
    $graph->img->SetImgFormat('png');
75
    $graph->SetScale("textlin");
76
    $graph->img->SetMargin(60, 60, 40, 140);
77
    $graph->img->SetAntiAliasing();
78
79
    $graph->SetShadow();
80
    $graph->ygrid->SetFill(false);
81
82
    // Setup dates as labels on the X-axis
83
    $graph->xaxis->SetTickLabels(array_keys($checkins));
84
    $graph->xaxis->HideTicks(false,false);
85
86
    $graph->yaxis->scale->SetAutoMin(0);
87
    $graph->yaxis->HideLine(false);
88
    $graph->yaxis->HideTicks(false,false);
89
    $graph->xaxis->SetLabelAngle(45);
90
    $graph->xaxis->SetFont(FF_ARIAL, FS_NORMAL, 10);
91
    $graph->yaxis->SetFont(FF_ARIAL, FS_NORMAL, 15);
92
93
94
    // format the data into something nicer
95
    $accum = [];
96
    foreach($checkins as $checkin_sum) {
97
      for($i = 1; $i <= 7; $i ++) {
98
        $accum[$i][] = array_key_exists($i, $checkin_sum) ? $checkin_sum[$i]['count'] : 0;
99
      }
100
    }
101
102
    // Create the bar plots
103
    $plots = [];
104
    $category = Yii::$container->get(\common\interfaces\CategoryInterface::class);
105
    foreach($accum as $category_key => $category_data) {
106
      $bplot = new BarPlot($category_data);
107
      $color = $category::$colors[$category_key]['color'];
108
109
      $bplot->SetColor($color);
110
      $bplot->SetFillColor($color);
111
      $bplot->SetLegend(($category::getCategories())[$category_key]);
112
113
      $plots[] = $bplot;
114
    }
115
116
    $gbbplot = new AccBarPlot($plots);
117
    $graph->Add($gbbplot);
118
119
    $graph->legend->SetColumns(3);
120
    $graph->legend->SetPos(0.5,0.98,'center','bottom'); // position it at the center, just above the bottom edge
121
122
    $img = $graph->Stroke(_IMG_HANDLER);
123
124
    ob_start();
125
    imagepng($img);
0 ignored issues
show
Bug introduced by
It seems like $img can also be of type false; however, parameter $image of imagepng() does only seem to accept GdImage|resource, maybe add an additional type check? ( Ignorable by Annotation )

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

125
    imagepng(/** @scrutinizer ignore-type */ $img);
Loading history...
126
    $img_data = ob_get_clean();
127
128
    if($toDisk) {
129
      $filepath = $this->getFilepath(); 
130
      if(!is_dir(dirname($filepath))) {
131
        mkdir(dirname($filepath), 0766, true);
132
      }
133
134
      file_put_contents($filepath, $img_data, LOCK_EX);
135
    }
136
137
    return $img_data;
138
  }
139
}
140