Less_Cache   B
last analyzed

Complexity

Total Complexity 47

Size/Duplication

Total Lines 305
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 47
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 305
rs 8.439

9 Methods

Rating   Name   Duplication   Size   Complexity  
D Get() 0 95 17
A OutputFile() 0 15 3
A CompiledName() 0 10 2
B CheckCacheDir() 0 19 5
C CleanCache() 0 58 11
A ListFiles() 0 13 2
A Regen() 0 4 1
B Cache() 0 32 5
A SetCacheDir() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Less_Cache 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 Less_Cache, and based on these observations, apply Extract Interface, too.

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 12 and the first side effect is on line 3.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
require_once( dirname(__FILE__).'/Version.php');
4
5
/**
6
 * Utility for handling the generation and caching of css files
7
 *
8
 * @package Less
9
 * @subpackage cache
10
 *
11
 */
12
class Less_Cache{
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
13
14
	// directory less.php can use for storing data
15
	public static $cache_dir	= false;
16
17
	// prefix for the storing data
18
	public static $prefix		= 'lessphp_';
19
20
	// prefix for the storing vars
21
	public static $prefix_vars	= 'lessphpvars_';
22
23
	// specifies the number of seconds after which data created by less.php will be seen as 'garbage' and potentially cleaned up
24
	public static $gc_lifetime	= 604800;
25
26
27
	/**
28
	 * Save and reuse the results of compiled less files.
29
	 * The first call to Get() will generate css and save it.
30
	 * Subsequent calls to Get() with the same arguments will return the same css filename
31
	 *
32
	 * @param array $less_files Array of .less files to compile
33
	 * @param array $parser_options Array of compiler options
34
	 * @param array $modify_vars Array of variables
35
	 * @return string Name of the css file
36
	 */
37
	public static function Get( $less_files, $parser_options = array(), $modify_vars = array() ){
38
39
40
		//check $cache_dir
41
		if( isset($parser_options['cache_dir']) ){
42
			Less_Cache::$cache_dir = $parser_options['cache_dir'];
43
		}
44
45
		if( empty(Less_Cache::$cache_dir) ){
46
			throw new Exception('cache_dir not set');
47
		}
48
49
		if( isset($parser_options['prefix']) ){
50
			Less_Cache::$prefix = $parser_options['prefix'];
51
		}
52
53
		if( empty(Less_Cache::$prefix) ){
54
			throw new Exception('prefix not set');
55
		}
56
57
		if( isset($parser_options['prefix_vars']) ){
58
			Less_Cache::$prefix_vars = $parser_options['prefix_vars'];
59
		}
60
61
		if( empty(Less_Cache::$prefix_vars) ){
62
			throw new Exception('prefix_vars not set');
63
		}
64
65
		self::CheckCacheDir();
66
		$less_files = (array)$less_files;
67
68
69
		//create a file for variables
70
		if( !empty($modify_vars) ){
71
			$lessvars = Less_Parser::serializeVars($modify_vars);
72
			$vars_file = Less_Cache::$cache_dir . Less_Cache::$prefix_vars . sha1($lessvars) . '.less';
73
74
			if( !file_exists($vars_file) ){
75
				file_put_contents($vars_file, $lessvars);
76
			}
77
78
			$less_files += array($vars_file => '/');
79
		}
80
81
82
		// generate name for compiled css file
83
		$hash = md5(json_encode($less_files));
84
 		$list_file = Less_Cache::$cache_dir . Less_Cache::$prefix . $hash . '.list';
85
86
87
 		// check cached content
88
 		if( !isset($parser_options['use_cache']) || $parser_options['use_cache'] === true ){
89
			if( file_exists($list_file) ){
90
91
				self::ListFiles($list_file, $list, $cached_name);
92
				$compiled_name = self::CompiledName($list);
93
94
				// if $cached_name is the same as the $compiled name, don't regenerate
95
				if( !$cached_name || $cached_name === $compiled_name ){
96
97
					$output_file = self::OutputFile($compiled_name, $parser_options );
98
99
					if( $output_file && file_exists($output_file) ){
100
						@touch($list_file);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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...
101
						return basename($output_file); // for backwards compatibility, we just return the name of the file
102
					}
103
				}
104
			}
105
		}
106
107
		$compiled = self::Cache( $less_files, $parser_options );
108
		if( !$compiled ){
109
			return false;
110
		}
111
112
		$compiled_name = self::CompiledName( $less_files );
113
		$output_file = self::OutputFile($compiled_name, $parser_options );
114
115
116
		//save the file list
117
		$list = $less_files;
118
		$list[] = $compiled_name;
119
		$cache = implode("\n",$list);
120
		file_put_contents( $list_file, $cache );
121
122
123
		//save the css
124
		file_put_contents( $output_file, $compiled );
125
126
127
		//clean up
128
		self::CleanCache();
129
130
		return basename($output_file);
131
	}
132
133
	/**
134
	 * Force the compiler to regenerate the cached css file
135
	 *
136
	 * @param array $less_files Array of .less files to compile
137
	 * @param array $parser_options Array of compiler options
138
	 * @param array $modify_vars Array of variables
139
	 * @return string Name of the css file
140
	 */
141
	public static function Regen( $less_files, $parser_options = array(), $modify_vars = array() ){
142
		$parser_options['use_cache'] = false;
143
		return self::Get( $less_files, $parser_options, $modify_vars );
144
	}
145
146
	public static function Cache( &$less_files, $parser_options = array() ){
147
148
149
		// get less.php if it exists
150
		$file = dirname(__FILE__) . '/Less.php';
151
		if( file_exists($file) && !class_exists('Less_Parser') ){
152
			require_once($file);
153
		}
154
155
		$parser_options['cache_dir'] = Less_Cache::$cache_dir;
156
		$parser = new Less_Parser($parser_options);
157
158
159
		// combine files
160
		foreach($less_files as $file_path => $uri_or_less ){
161
162
			//treat as less markup if there are newline characters
163
			if( strpos($uri_or_less,"\n") !== false ){
164
				$parser->Parse( $uri_or_less );
165
				continue;
166
			}
167
168
			$parser->ParseFile( $file_path, $uri_or_less );
169
		}
170
171
		$compiled = $parser->getCss();
172
173
174
		$less_files = $parser->allParsedFiles();
175
176
		return $compiled;
177
	}
178
179
180
	private static function OutputFile( $compiled_name, $parser_options ){
181
182
		//custom output file
183
		if( !empty($parser_options['output']) ){
184
185
			//relative to cache directory?
186
			if( preg_match('#[\\\\/]#',$parser_options['output']) ){
187
				return $parser_options['output'];
188
			}
189
190
			return Less_Cache::$cache_dir.$parser_options['output'];
191
		}
192
193
		return Less_Cache::$cache_dir.$compiled_name;
194
	}
195
196
197
	private static function CompiledName( $files ){
198
199
		//save the file list
200
		$temp = array(Less_Version::cache_version);
201
		foreach($files as $file){
202
			$temp[] = filemtime($file)."\t".filesize($file)."\t".$file;
203
		}
204
205
		return Less_Cache::$prefix.sha1(json_encode($temp)).'.css';
206
	}
207
208
209
	public static function SetCacheDir( $dir ){
210
		Less_Cache::$cache_dir = $dir;
211
	}
212
213
	public static function CheckCacheDir(){
214
215
		Less_Cache::$cache_dir = str_replace('\\','/',Less_Cache::$cache_dir);
0 ignored issues
show
Documentation Bug introduced by
The property $cache_dir was declared of type boolean, but str_replace('\\', '/', \Less_Cache::$cache_dir) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
216
		Less_Cache::$cache_dir = rtrim(Less_Cache::$cache_dir,'/').'/';
0 ignored issues
show
Documentation Bug introduced by
The property $cache_dir was declared of type boolean, but rtrim(\Less_Cache::$cache_dir, '/') . '/' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
217
218
		if( !file_exists(Less_Cache::$cache_dir) ){
219
			if( !mkdir(Less_Cache::$cache_dir) ){
220
				throw new Less_Exception_Parser('Less.php cache directory couldn\'t be created: '.Less_Cache::$cache_dir);
221
			}
222
223
		}elseif( !is_dir(Less_Cache::$cache_dir) ){
224
			throw new Less_Exception_Parser('Less.php cache directory doesn\'t exist: '.Less_Cache::$cache_dir);
225
226
		}elseif( !is_writable(Less_Cache::$cache_dir) ){
227
			throw new Less_Exception_Parser('Less.php cache directory isn\'t writable: '.Less_Cache::$cache_dir);
228
229
		}
230
231
	}
232
233
234
	/**
235
	 * Delete unused less.php files
236
	 *
237
	 */
238
	public static function CleanCache(){
239
		static $clean = false;
240
241
		if( $clean ){
242
			return;
243
		}
244
245
		$files = scandir(Less_Cache::$cache_dir);
246
		if( $files ){
0 ignored issues
show
Bug Best Practice introduced by
The expression $files 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...
247
			$check_time = time() - self::$gc_lifetime;
248
			foreach($files as $file){
249
250
				// don't delete if the file wasn't created with less.php
251
				if( strpos($file,Less_Cache::$prefix) !== 0 ){
252
					continue;
253
				}
254
255
				$full_path = Less_Cache::$cache_dir . $file;
256
257
				// make sure the file still exists
258
				// css files may have already been deleted
259
				if( !file_exists($full_path) ){
260
					continue;
261
				}
262
				$mtime = filemtime($full_path);
263
264
				// don't delete if it's a relatively new file
265
				if( $mtime > $check_time ){
266
					continue;
267
				}
268
269
				$parts = explode('.',$file);
270
				$type = array_pop($parts);
271
272
273
				// delete css files based on the list files
274
				if( $type === 'css' ){
275
					continue;
276
				}
277
278
279
				// delete the list file and associated css file
280
				if( $type === 'list' ){
281
					self::ListFiles($full_path, $list, $css_file_name);
282
					if( $css_file_name ){
283
						$css_file = Less_Cache::$cache_dir . $css_file_name;
284
						if( file_exists($css_file) ){
285
							unlink($css_file);
286
						}
287
					}
288
				}
289
290
				unlink($full_path);
291
			}
292
		}
293
294
		$clean = true;
295
	}
296
297
298
	/**
299
	 * Get the list of less files and generated css file from a list file
300
	 *
301
	 */
302
	static function ListFiles($list_file, &$list, &$css_file_name ){
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
303
304
		$list = explode("\n",file_get_contents($list_file));
305
306
		//pop the cached name that should match $compiled_name
307
		$css_file_name = array_pop($list);
308
309
		if( !preg_match('/^' . Less_Cache::$prefix . '[a-f0-9]+\.css$/',$css_file_name) ){
310
			$list[] = $css_file_name;
311
			$css_file_name = false;
312
		}
313
314
	}
315
316
}
317