Completed
Push — address-as-title ( 9b6eeb...601934 )
by Peter
11:07
created

MapsParamOLLayers::manipulate()   D

Complexity

Conditions 19
Paths 24

Size

Total Lines 99
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 99
rs 4.764
cc 19
eloc 51
nc 24
nop 2

How to fix   Long Method    Complexity   

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
3
/**
4
 * Parameter manipulation ensuring the value is
5
 *
6
 * @since 0.7
7
 *
8
 * @file Maps_ParamOLLayers.php
9
 * @ingroup Maps
10
 * @ingroup ParameterManipulations
11
 * @ingroup MapsOpenLayers
12
 *
13
 * @licence GNU GPL v2+
14
 * @author Jeroen De Dauw < [email protected] >
15
 * @author Daniel Werner
16
 */
17
class MapsParamOLLayers extends ListParameterManipulation {
18
	
19
	/**
20
	 * @since 3.0
21
	 *
22
	 * @var string
23
	 */
24
	protected $groupNameSep;
25
26
	/**
27
	 * Constructor.
28
	 *
29
	 * @param string $groupNameSeparator Separator between layer group and the
30
	 *        layers name within the group.
31
	 *
32
	 * @since 0.7
33
	 */
34
	public function __construct( $groupNameSeparator = ';' ) {
35
		parent::__construct();
36
		$this->groupNameSep = $groupNameSeparator;
37
	}
38
	
39
	/**
40
	 * @see ParameterManipulation::manipulate
41
	 *
42
	 * @since 0.7
43
	 */
44
	public function manipulate( Parameter &$parameter, array &$parameters ) {
45
		global $egMapsOLLayerGroups, $egMapsOLAvailableLayers;
46
		
47
		$layerDefs = [];
48
		$usedLayers = [];
49
		
50
		foreach ( $parameter->getValue() as $layerOrGroup ) {
51
			$lcLayerOrGroup = strtolower( $layerOrGroup );
52
			
53
			// Layer groups. Loop over all items and add them if not present yet.
54
			if ( array_key_exists( $lcLayerOrGroup, $egMapsOLLayerGroups ) ) {
55
				foreach ( $egMapsOLLayerGroups[$lcLayerOrGroup] as $layerName ) {
56
					if ( !in_array( $layerName, $usedLayers ) ) {
57
						if ( is_array( $egMapsOLAvailableLayers[$layerName] ) ) {
58
							$layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$layerName][0];
59
						}
60
						else {
61
							$layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$layerName];
62
						}
63
						$usedLayers[] = $layerName;
64
					}
65
				}
66
			}
67
			// Single layers. Add them if not present yet.
68
			elseif ( array_key_exists( $lcLayerOrGroup, $egMapsOLAvailableLayers ) ) {
69
				if ( !in_array( $lcLayerOrGroup, $usedLayers ) ) {
70
					if ( is_array( $egMapsOLAvailableLayers[$lcLayerOrGroup] ) ) {
71
						$layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$lcLayerOrGroup][0];
72
					}
73
					else {
74
						$layerDefs[] = 'new ' . $egMapsOLAvailableLayers[$lcLayerOrGroup];
75
					}
76
					
77
					$usedLayers[] = $lcLayerOrGroup;
78
				}
79
			}
80
			// Image layers. Check validity and add if not present yet.
81
			else {
82
				$layerParts = explode( $this->groupNameSep, $layerOrGroup, 2 );
83
				$layerGroup = $layerParts[0];
84
				$layerName = count( $layerParts ) > 1 ? $layerParts[1] : null;
85
86
				$title = Title::newFromText( $layerGroup, Maps_NS_LAYER );
87
88
				if ( $title !== null && $title->getNamespace() == Maps_NS_LAYER ) {
89
					/**
90
					 * TODO/FIXME: This shouldn't be here and using $wgParser, instead it should
91
					 * be somewhere around MapsBaseMap::renderMap. But since we do a lot more than
92
					 * 'parameter manipulation' in here, we already diminish the information needed
93
					 * for this which will never arrive there. Perhaps the whole
94
					 * MapsLayer::getJavaScriptDefinition() shouldn't be done here.
95
					 */
96
					global $wgParser;
97
					// add dependency to the layer page so if the layer definition gets updated,
98
					// the page where it is used will be updated as well:
99
					$rev = Revision::newFromTitle( $title );
100
					$wgParser->getOutput()->addTemplate( $title, $title->getArticleID(), $rev->getId() );
101
102
					// if the whole layer group is not yet loaded into the map and the group exists:
103
					if( ! in_array( $layerGroup, $usedLayers )
104
						&& $title->exists()
105
					) {
106
						$layerPage = new MapsLayerPage( $title );
0 ignored issues
show
Unused Code introduced by
$layerPage is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
107
108
						if( $layerName !== null ) {
109
							// load specific layer with name:
110
							$layer = MapsLayers::loadLayer( $title, $layerName );
111
							$layers = new MapsLayerGroup( $layer );
0 ignored issues
show
Bug introduced by
It seems like $layer defined by \MapsLayers::loadLayer($title, $layerName) on line 110 can be null; however, MapsLayerGroup::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
112
							$usedLayer = $layerOrGroup;
113
						}
114
						else {
115
							// load all layers from group:
116
							$layers = MapsLayers::loadLayerGroup( $title );
117
							$usedLayer = $layerGroup;
118
						}
119
120
						foreach( $layers->getLayers() as $layer ) {
121
							if( ( // make sure named layer is only taken once (in case it was requested on its own before)
122
								$layer->getName() === null
123
									|| ! in_array( $layerGroup . $this->groupNameSep . $layer->getName(), $usedLayers )
124
							)
125
								&& $layer->isOk()
126
							) {
127
								$layerDefs[] = $layer->getJavaScriptDefinition();
128
							}
129
						}
130
						$usedLayers[] = $usedLayer; // have to add this after loop of course!
131
					}
132
				}
133
				else {
134
					wfWarn( "Invalid layer ($layerOrGroup) encountered after validation." );
135
				}
136
			}
137
		}
138
		
139
		$parameter->setValue( $layerDefs );
140
		
141
		MapsMappingServices::getServiceInstance( 'openlayers' )->addLayerDependencies( $this->getDependencies( $usedLayers ) );
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface iMappingService as the method addLayerDependencies() does only exist in the following implementations of said interface: MapsOpenLayers.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
142
	}
143
	
144
	/**
145
	 * Returns the depencies for the provided layers.
146
	 *
147
	 * @since 0.7.1
148
	 *
149
	 * @param array $layerNames
150
	 *
151
	 * @return array
152
	 */
153
	protected function getDependencies( array $layerNames ) {
154
		global $egMapsOLLayerDependencies, $egMapsOLAvailableLayers;
155
		
156
		$layerDependencies = [];
157
		
158
		foreach ( $layerNames as $layerName ) {
159
			if ( array_key_exists( $layerName, $egMapsOLAvailableLayers ) // The layer must be defined in php
160
				&& is_array( $egMapsOLAvailableLayers[$layerName] ) // The layer must be an array...
161
				&& count( $egMapsOLAvailableLayers[$layerName] ) > 1 // ...with a second element...
162
				&& array_key_exists( $egMapsOLAvailableLayers[$layerName][1], $egMapsOLLayerDependencies ) ) { //...that is a dependency.
163
				$layerDependencies[] = $egMapsOLLayerDependencies[$egMapsOLAvailableLayers[$layerName][1]];
164
			}
165
		}
166
167
		return array_unique( $layerDependencies );
168
	}
169
	
170
}
171