Completed
Push — master ( 7eb8b3...c1c676 )
by Lukas
12:54
created

CSSResourceLocator   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 132
Duplicated Lines 31.06 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 41
loc 132
rs 10
c 0
b 0
f 0
wmc 27
lcom 1
cbo 5

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
D doFind() 7 27 10
A doFindTheme() 0 6 3
A cacheAndAppendScssIfExist() 0 18 4
C append() 34 46 9

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bart Visscher <[email protected]>
6
 * @author Joas Schilling <[email protected]>
7
 * @author Morris Jobke <[email protected]>
8
 * @author Thomas Müller <[email protected]>
9
 *
10
 * @license AGPL-3.0
11
 *
12
 * This code is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License, version 3,
14
 * as published by the Free Software Foundation.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License, version 3,
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
23
 *
24
 */
25
26
namespace OC\Template;
27
28
use OCP\ILogger;
29
30
class CSSResourceLocator extends ResourceLocator {
31
32
	/** @var SCSSCacher */
33
	protected $scssCacher;
34
35
	/**
36
	 * @param ILogger $logger
37
	 * @param string $theme
38
	 * @param array $core_map
39
	 * @param array $party_map
40
	 * @param SCSSCacher $scssCacher
41
	 */
42
	public function __construct(ILogger $logger, $theme, $core_map, $party_map, $scssCacher) {
43
		$this->scssCacher = $scssCacher;
44
45
		parent::__construct($logger, $theme, $core_map, $party_map);
46
	}
47
48
	/**
49
	 * @param string $style
50
	 */
51
	public function doFind($style) {
52
		$app = substr($style, 0, strpos($style, '/'));
53
		if (strpos($style, '3rdparty') === 0
54
			&& $this->appendIfExist($this->thirdpartyroot, $style.'.css')
55
			|| $this->cacheAndAppendScssIfExist($this->serverroot, $style.'.scss', $app)
56
			|| $this->cacheAndAppendScssIfExist($this->serverroot, 'core/'.$style.'.scss')
57
			|| $this->appendIfExist($this->serverroot, $style.'.css')
58
			|| $this->appendIfExist($this->serverroot, 'core/'.$style.'.css')
59
		) {
60
			return;
61
		}
62
		$style = substr($style, strpos($style, '/')+1);
63
		$app_path = \OC_App::getAppPath($app);
64
		$app_url = \OC_App::getAppWebPath($app);
65
66 View Code Duplication
		if ($app_path === false && $app_url === false) {
67
			$this->logger->error('Could not find resource {resource} to load', [
68
				'resource' => $app . '/' . $style . '.css',
69
				'app' => 'cssresourceloader',
70
			]);
71
			return;
72
		}
73
74
		if(!$this->cacheAndAppendScssIfExist($app_path, $style.'.scss', $app)) {
0 ignored issues
show
Security Bug introduced by
It seems like $app_path defined by \OC_App::getAppPath($app) on line 63 can also be of type false; however, OC\Template\CSSResourceL...eAndAppendScssIfExist() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
75
			$this->append($app_path, $style.'.css', $app_url);
76
		}
77
	}
78
79
	/**
80
	 * @param string $style
81
	 */
82
	public function doFindTheme($style) {
83
		$theme_dir = 'themes/'.$this->theme.'/';
84
		$this->appendIfExist($this->serverroot, $theme_dir.'apps/'.$style.'.css')
85
			|| $this->appendIfExist($this->serverroot, $theme_dir.$style.'.css')
86
			|| $this->appendIfExist($this->serverroot, $theme_dir.'core/'.$style.'.css');
87
	}
88
89
	/**
90
	 * cache and append the scss $file if exist at $root
91
	 *
92
	 * @param string $root path to check
93
	 * @param string $file the filename
94
	 * @return bool True if the resource was found and cached, false otherwise
95
	 */
96
	protected function cacheAndAppendScssIfExist($root, $file, $app = 'core') {
97
		if (is_file($root.'/'.$file)) {
98
			if($this->scssCacher !== null) {
99
				if($this->scssCacher->process($root, $file, $app)) {
100
101
					$this->append($root, $this->scssCacher->getCachedSCSS($app, $file), false, true, true);
102
					return true;
103
				} else {
104
					$this->logger->warning('Failed to compile and/or save '.$root.'/'.$file, ['app' => 'core']);
105
					return false;
106
				}
107
			} else {
108
				$this->logger->debug('Scss is disabled for '.$root.'/'.$file.', ignoring', ['app' => 'core']);
109
				return true;
110
			}
111
		}
112
		return false;
113
	}
114
115
	public function append($root, $file, $webRoot = null, $throw = true, $scss = false) {
116
		if (!$scss) {
117
			parent::append($root, $file, $webRoot, $throw);
118
		} else {
119 View Code Duplication
			if (!$webRoot) {
120
				$tmpRoot = $root;
121
				/*
122
				 * traverse the potential web roots upwards in the path
123
				 *
124
				 * example:
125
				 *   - root: /srv/www/apps/myapp
126
				 *   - available mappings: ['/srv/www']
127
				 *
128
				 * First we check if a mapping for /srv/www/apps/myapp is available,
129
				 * then /srv/www/apps, /srv/www/apps, /srv/www, ... until we find a
130
				 * valid web root
131
				 */
132
				do {
133
					if (isset($this->mapping[$tmpRoot])) {
134
						$webRoot = $this->mapping[$tmpRoot];
135
						break;
136
					}
137
138
					if ($tmpRoot === '/') {
139
						$webRoot = '';
140
						$this->logger->error('ResourceLocator can not find a web root (root: {root}, file: {file}, webRoot: {webRoot}, throw: {throw})', [
141
							'app' => 'lib',
142
							'root' => $root,
143
							'file' => $file,
144
							'webRoot' => $webRoot,
145
							'throw' => $throw ? 'true' : 'false'
146
						]);
147
						break;
148
					}
149
					$tmpRoot = dirname($tmpRoot);
150
				} while(true);
151
152
			}
153
154
			if ($throw && $tmpRoot === '/') {
0 ignored issues
show
Bug introduced by
The variable $tmpRoot does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
155
				throw new ResourceNotFoundException($file, $webRoot);
156
			}
157
158
			$this->resources[] = array($tmpRoot, $webRoot, $file);
159
		}
160
	}
161
}
162