Template   B
last analyzed

Complexity

Total Complexity 43

Size/Duplication

Total Lines 209
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 43
lcom 1
cbo 1
dl 0
loc 209
ccs 0
cts 118
cp 0
rs 8.96
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getFullpath() 0 8 2
A getThemes() 0 9 5
A getDesigns() 0 10 4
A cachedGetActiveTemplates() 0 6 2
A getActiveTemplates() 0 16 5
A getTemplateContent() 0 5 1
A getTemplateFiles() 0 14 2
A getTemplatesTree() 0 12 3
B _getTemplatesTreeRecursive() 0 20 7
A getEntry() 0 11 5
A getEntryMTime() 0 9 3
A updateEntry() 0 10 4

How to fix   Complexity   

Complex Class

Complex classes like Template often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Template, and based on these observations, apply Extract Interface, too.

1
<?php
2
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
3
4
class Template extends Base {
5
  protected $table = 'templates';
6
  /**
7
   * Get filepath for template name based on current PAGE and ACTION
8
   */
9
  public function getFullpath($name) {
10
    $chunks = array(PAGE);
11
    if( ACTION )
12
      $chunks[] = ACTION;
13
    $chunks[] = $name;
14
15
    return join('/', $chunks);
16
  }
17
18
  /**
19
   * Get all available themes
20
   * Read theme folders from TEMPLATE_DIR
21
   *
22
   * @return array - list of available themes
23
   */
24
  public function getThemes() {
25
    $this->debug->append("STA " . __METHOD__, 4);
26
    $aTmpThemes = glob(TEMPLATE_DIR . '/*');
27
    $aThemes = array();
28
    foreach ($aTmpThemes as $dir) {
29
      if (basename($dir) != 'cache' && basename($dir) != 'compile' && basename($dir) != 'mail') $aThemes[basename($dir)] = basename($dir);
30
    }
31
    return $aThemes;
32
  }
33
34
  /**
35
   * Get all available designs
36
   * Read css files from css/design folder
37
   *
38
   * @return array - list of available designs
39
   */
40
  public function getDesigns() {
41
    $this->debug->append("STA " . __METHOD__, 4);
42
    $aTmpDesigns = glob(BASEPATH . 'site_assets/' . THEME . '/css/design/*.css');
43
    $aDesigns = array();
44
    $aDesigns['default'] = 'default';
45
    foreach ($aTmpDesigns as $filename) {
46
      if (basename($filename) != '.' && basename($filename) != '..') $aDesigns[basename($filename, ".css")] = basename($filename, ".css");
47
    }
48
    return $aDesigns;
49
  }
50
  
51
  /**
52
   * Cached getActiveTemplates method
53
   *
54
   * @see getActiveTemplates
55
   */
56
  private static $active_templates;
57
  public function cachedGetActiveTemplates() {
58
      if ( is_null(self::$active_templates) ) {
59
          self::$active_templates = $this->getActiveTemplates();
60
      }
61
      return self::$active_templates;
62
  }
63
  /**
64
   * Return the all active templates as hash,
65
   * where key is template and value is modified_at
66
   *
67
   * @return array - list of active templates
68
   */
69
  public function getActiveTemplates() {
70
    $this->debug->append("STA " . __METHOD__, 4);
71
    $stmt = $this->mysqli->prepare("SELECT template, modified_at FROM $this->table WHERE active = 1");
72
    if ($stmt && $stmt->execute() && $result = $stmt->get_result()) {
73
      $rows = $result->fetch_all(MYSQLI_ASSOC);
74
      $hash = array();
75
      foreach($rows as $row) {
76
          $hash[$row['template']] = strtotime($row['modified_at']);
77
      }
78
      return $hash;
79
    }
80
81
    $this->setErrorMessage('Failed to get active templates');
82
    $this->debug->append('Template::getActiveTemplates failed: ' . $this->mysqli->lastused->error);
83
    return false;
84
  }
85
86
  /**
87
   * Return the content of specific template file
88
   *
89
   * @param $file - file of template related to TEMPLATE_DIR
90
   * @return string - content of the template file
91
   */
92
  public function getTemplateContent($file) {
93
    $this->debug->append("STA " . __METHOD__, 4);
94
    $filepath = TEMPLATE_DIR . '/' . $file;
95
    return file_get_contents($filepath);
96
  }
97
98
  /**
99
   * Get all possible templates of specific theme
100
   *
101
   * @param $theme - name of the theme
102
   * @return array - list of available templates of theme
103
   */
104
  public function getTemplateFiles($theme) {
105
    $this->debug->append("STA " . __METHOD__, 4);
106
    $folder = TEMPLATE_DIR . '/' . $theme;
107
108
    $dir = new RecursiveDirectoryIterator($folder);
109
    $ite = new RecursiveIteratorIterator($dir);
110
    $files = new RegexIterator($ite, '!'.preg_quote($folder, '!').'/(.*\.tpl$)!', RegexIterator::GET_MATCH);
111
    $fileList = array();
112
    foreach($files as $file) {
113
        $fileList[] = $theme . '/' . $file[1];
114
    }
115
116
    return $fileList;
117
  }
118
119
  /**
120
   * Get tree of all possible templates, where key is filename
121
   * and value is whether array of subfiles if filename is directory
122
   * or true, if filename is file
123
   *
124
   * @param $themes - optional, themes array
125
   * @return array - tree of all templates
126
   */
127
  public function getTemplatesTree($themes = null) {
128
    if( is_null($themes) )
129
      $themes = $this->getThemes();
130
131
    $templates = array();
132
    foreach($themes as $theme) {
133
      $templates[$theme] = $this->_getTemplatesTreeRecursive(TEMPLATE_DIR . '/' . $theme);
134
    }
135
136
    return $templates;
137
138
  }
139
140
  private function _getTemplatesTreeRecursive($path) {
141
    if( !is_dir($path) ) {
142
      return preg_match("/\.tpl$/", $path);
143
    } else {
144
      $subfiles = scandir($path);
145
      if ( $subfiles === false )
146
        return false;
147
148
      $files = array();
149
      foreach($subfiles as $subfile) {
150
        if($subfile == ".." || $subfile == ".") continue;
151
        $subpath = $path . '/' . $subfile;
152
        $subsubfiles = $this->_getTemplatesTreeRecursive($subpath);
153
        if ( !$subsubfiles ) continue;
154
        $files[$subfile] = $subsubfiles;
155
      }
156
      return $files;
157
    }
158
    return array();
0 ignored issues
show
Unused Code introduced by
return array(); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
159
  }
160
161
  /**
162
   * Return specific template from database
163
   *
164
   * @param $template - name (filepath) of the template
165
   * @return array - result from database
166
   */
167
  public function getEntry($template, $columns = "*") {
168
    $this->debug->append("STA " . __METHOD__, 4);
169
170
    $stmt = $this->mysqli->prepare("SELECT $columns FROM $this->table WHERE template = ?");
171
    if ($stmt && $stmt->bind_param('s', $template) && $stmt->execute() && $result = $stmt->get_result())
172
      return $result->fetch_assoc();
173
174
    $this->setErrorMessage('Failed to get the template');
175
    $this->debug->append('Template::getEntry failed: ' . $this->mysqli->lastused->error);
176
    return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Template::getEntry of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
177
  }
178
179
  /**
180
   * Return last modified time of specific template from database
181
   *
182
   * @param $template - name (filepath) of the template
183
   * @return timestamp - last modified time of template
184
   */
185
  public function getEntryMTime($template) {
186
    $this->debug->append("STA " . __METHOD__, 4);
187
188
    $entry = $this->getEntry($template, "modified_at, active");
189
    if ( $entry && $entry['active'])
0 ignored issues
show
Bug Best Practice introduced by
The expression $entry of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
190
        return strtotime($entry['modified_at']);
191
192
    return false;
193
  }
194
195
  /**
196
   * Update template in database
197
   *
198
   * @param $template - name (filepath) of the template
199
   * @param $content - content of the template
200
   * @param $active - active flag for the template
201
   **/
202
  public function updateEntry($template, $content, $active=0) {
203
    $this->debug->append("STA " . __METHOD__, 4);
204
    $stmt = $this->mysqli->prepare("INSERT INTO $this->table (`template`, `content`, `active`, `modified_at`) VALUES(?, ?, ?, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE content = VALUES(content), active = VALUES(active), modified_at = CURRENT_TIMESTAMP");
205
    if ($stmt && $stmt->bind_param('ssi', $template, $content, $active) && $stmt->execute())
206
      return true;
207
208
    $this->setErrorMessage('Database error');
209
    $this->debug->append('Template::updateEntry failed: ' . $this->mysqli->lastused->error);
210
    return false;
211
  }
212
}
213
214
$template = new Template();
215
$template->setDebug($debug);
216
$template->setMysql($mysqli);
217