ObjectFactory::constructClassInstance()   C
last analyzed

Complexity

Conditions 14
Paths 13

Size

Total Lines 69
Code Lines 53

Duplication

Lines 12
Ratio 17.39 %

Importance

Changes 0
Metric Value
cc 14
eloc 53
nc 13
nop 2
dl 12
loc 69
rs 5.6823
c 0
b 0
f 0

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
 * This program is free software; you can redistribute it and/or modify
4
 * it under the terms of the GNU General Public License as published by
5
 * the Free Software Foundation; either version 2 of the License, or
6
 * (at your option) any later version.
7
 *
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
 * GNU General Public License for more details.
12
 *
13
 * You should have received a copy of the GNU General Public License along
14
 * with this program; if not, write to the Free Software Foundation, Inc.,
15
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16
 * http://www.gnu.org/copyleft/gpl.html
17
 *
18
 * @file
19
 */
20
21
/**
22
 * Construct objects from configuration instructions.
23
 *
24
 * @author Bryan Davis <[email protected]>
25
 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
26
 */
27
class ObjectFactory {
28
29
	/**
30
	 * Instantiate an object based on a specification array.
31
	 *
32
	 * The specification array must contain a 'class' key with string value
33
	 * that specifies the class name to instantiate or a 'factory' key with
34
	 * a callable (is_callable() === true). It can optionally contain
35
	 * an 'args' key that provides arguments to pass to the
36
	 * constructor/callable.
37
	 *
38
	 * Values in the arguments collection which are Closure instances will be
39
	 * expanded by invoking them with no arguments before passing the
40
	 * resulting value on to the constructor/callable. This can be used to
41
	 * pass IDatabase instances or other live objects to the
42
	 * constructor/callable. This behavior can be suppressed by adding
43
	 * closure_expansion => false to the specification.
44
	 *
45
	 * The specification may also contain a 'calls' key that describes method
46
	 * calls to make on the newly created object before returning it. This
47
	 * pattern is often known as "setter injection". The value of this key is
48
	 * expected to be an associative array with method names as keys and
49
	 * argument lists as values. The argument list will be expanded (or not)
50
	 * in the same way as the 'args' key for the main object.
51
	 *
52
	 * @param array $spec Object specification
53
	 * @return object
54
	 * @throws InvalidArgumentException when object specification does not
55
	 * contain 'class' or 'factory' keys
56
	 * @throws ReflectionException when 'args' are supplied and 'class'
57
	 * constructor is non-public or non-existent
58
	 */
59
	public static function getObjectFromSpec( $spec ) {
60
		$args = isset( $spec['args'] ) ? $spec['args'] : [];
61
		$expandArgs = !isset( $spec['closure_expansion'] ) ||
62
			$spec['closure_expansion'] === true;
63
64
		if ( $expandArgs ) {
65
			$args = static::expandClosures( $args );
66
		}
67
68
		if ( isset( $spec['class'] ) ) {
69
			$clazz = $spec['class'];
70
			if ( !$args ) {
71
				$obj = new $clazz();
72
			} else {
73
				$obj = static::constructClassInstance( $clazz, $args );
74
			}
75
		} elseif ( isset( $spec['factory'] ) ) {
76
			$obj = call_user_func_array( $spec['factory'], $args );
77
		} else {
78
			throw new InvalidArgumentException(
79
				'Provided specification lacks both factory and class parameters.'
80
			);
81
		}
82
83
		if ( isset( $spec['calls'] ) && is_array( $spec['calls'] ) ) {
84
			// Call additional methods on the newly created object
85
			foreach ( $spec['calls'] as $method => $margs ) {
86
				if ( $expandArgs ) {
87
					$margs = static::expandClosures( $margs );
88
				}
89
				call_user_func_array( [ $obj, $method ], $margs );
90
			}
91
		}
92
93
		return $obj;
94
	}
95
96
	/**
97
	 * Iterate a list and call any closures it contains.
98
	 *
99
	 * @param array $list List of things
100
	 * @return array List with any Closures replaced with their output
101
	 */
102
	protected static function expandClosures( $list ) {
103
		return array_map( function ( $value ) {
104
			if ( is_object( $value ) && $value instanceof Closure ) {
105
				// If $value is a Closure, call it.
106
				return $value();
107
			} else {
108
				return $value;
109
			}
110
		}, $list );
111
	}
112
113
	/**
114
	 * Construct an instance of the given class using the given arguments.
115
	 *
116
	 * PHP's `call_user_func_array()` doesn't work with object construction so
117
	 * we have to use other measures. Starting with PHP 5.6.0 we could use the
118
	 * "splat" operator (`...`) to unpack the array into an argument list.
119
	 * Sadly there is no way to conditionally include a syntax construct like
120
	 * a new operator in a way that allows older versions of PHP to still
121
	 * parse the file. Instead, we will try a loop unrolling technique that
122
	 * works for 0-10 arguments. If we are passed 11 or more arguments we will
123
	 * take the performance penalty of using
124
	 * `ReflectionClass::newInstanceArgs()` to construct the desired object.
125
	 *
126
	 * @param string $clazz Class name
127
	 * @param array $args Constructor arguments
128
	 * @return mixed Constructed instance
129
	 */
130
	public static function constructClassInstance( $clazz, $args ) {
131
		// $args should be a non-associative array; show nice error if that's not the case
132
		if ( $args && array_keys( $args ) !== range( 0, count( $args ) - 1 ) ) {
133
			throw new InvalidArgumentException( __METHOD__ . ': $args cannot be an associative array' );
134
		}
135
136
		// TODO: when PHP min version supported is >=5.6.0 replace this
137
		// with `return new $clazz( ... $args );`.
138
		$obj = null;
0 ignored issues
show
Unused Code introduced by
$obj 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...
139
		switch ( count( $args ) ) {
140
			case 0:
141
				$obj = new $clazz();
142
				break;
143
			case 1:
144
				$obj = new $clazz( $args[0] );
145
				break;
146
			case 2:
147
				$obj = new $clazz( $args[0], $args[1] );
148
				break;
149
			case 3:
150
				$obj = new $clazz( $args[0], $args[1], $args[2] );
151
				break;
152
			case 4:
153
				$obj = new $clazz( $args[0], $args[1], $args[2], $args[3] );
154
				break;
155
			case 5:
156
				$obj = new $clazz(
157
					$args[0], $args[1], $args[2], $args[3], $args[4]
158
				);
159
				break;
160
			case 6:
161
				$obj = new $clazz(
162
					$args[0], $args[1], $args[2], $args[3], $args[4],
163
					$args[5]
164
				);
165
				break;
166
			case 7:
167
				$obj = new $clazz(
168
					$args[0], $args[1], $args[2], $args[3], $args[4],
169
					$args[5], $args[6]
170
				);
171
				break;
172
			case 8:
173
				$obj = new $clazz(
174
					$args[0], $args[1], $args[2], $args[3], $args[4],
175
					$args[5], $args[6], $args[7]
176
				);
177
				break;
178 View Code Duplication
			case 9:
179
				$obj = new $clazz(
180
					$args[0], $args[1], $args[2], $args[3], $args[4],
181
					$args[5], $args[6], $args[7], $args[8]
182
				);
183
				break;
184 View Code Duplication
			case 10:
185
				$obj = new $clazz(
186
					$args[0], $args[1], $args[2], $args[3], $args[4],
187
					$args[5], $args[6], $args[7], $args[8], $args[9]
188
				);
189
				break;
190
			default:
191
				// Fall back to using ReflectionClass and curse the developer
192
				// who decided that 11+ args was a reasonable method
193
				// signature.
194
				$ref = new ReflectionClass( $clazz );
195
				$obj = $ref->newInstanceArgs( $args );
196
		}
197
		return $obj;
198
	}
199
}
200